Top Banner
Introduction to Programming in C# John Galletly
59

Introduction to Programming in C# John Galletly. The Basics.

Dec 31, 2015

Download

Documents

Caren Grant
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Introduction to Programming in C# John Galletly. The Basics.

Introduction to Programmingin C#

John Galletly

Page 2: Introduction to Programming in C# John Galletly. The Basics.

The Basics

Page 3: Introduction to Programming in C# John Galletly. The Basics.

What is "C#"?

• “Flagship” language for Microsoft’s .NET Framework

• C# features:

– New cutting edge language

– Extremely powerful

– Easy to learn

– Easy to read and understand

– Object-oriented

Page 4: Introduction to Programming in C# John Galletly. The Basics.

Why C#?

• Can be used to develop a number of different types of applications– Software components– Mobile applications– Dynamic Web pages– Database access components– Windows desktop applications– Web services– Console-based applications

Page 5: Introduction to Programming in C# John Galletly. The Basics.

Syntax – Writing C# Programs

In a lot of areas, C# and Java are syntactically similar to each other, and also similar to C and C++.

However, there are differences between C# and the other languages

- Some of which are infuriating!

Page 6: Introduction to Programming in C# John Galletly. The Basics.

Object-Oriented Programming

• Construct complex systems that model real-world entities

• Facilitates designing components

• Assumption is that the world contains a number of entities that can be identified and described by software objects

Page 7: Introduction to Programming in C# John Galletly. The Basics.

Microsoft’s .NET Framework

• Not an operating system

• An environment in which programs run

• Resides at a layer between operating system and other applications

• Offers multilanguage independence – One application can be written in more than one language

• Includes over 2,500 reusable types (classes)

• Enables creation of dynamic Web pages and Web services

• Scalable component development

Page 8: Introduction to Programming in C# John Galletly. The Basics.

What is .NET Framework?

• Environment for execution of Micrsoft .NET programs

• Powerful library of classes

• Programming model

• Common execution engine for many programming languages– C#– Visual Basic .NET– ... and many others

Page 9: Introduction to Programming in C# John Galletly. The Basics.

Inside .NET Framework

Page 10: Introduction to Programming in C# John Galletly. The Basics.

Console Applications

• Normally send requests to the operating system

• Display text on the command console

• Easiest to create

– Simplest approach to learning software development

– Minimal overhead for input and output of data

Page 11: Introduction to Programming in C# John Galletly. The Basics.

Windows Applications

• Applications designed for the desktop

• Designed for a single platform

• Use classes from System.Windows.Form

• Applications can include menus, pictures, drop-down controls, buttons, text boxes, and labels

• Use drag-and-drop feature of Visual Studio

Page 12: Introduction to Programming in C# John Galletly. The Basics.

Web Applications

• C# was designed with the Internet applications in mind

• Can quickly build applications that run on the Web with C#

– Using Web Forms: part of ASP.NET

Page 13: Introduction to Programming in C# John Galletly. The Basics.

Visual Studio .NET (VS.NET)

• A single IDE for all forms of .NET development– From class libraries to form-based apps to web services– And using C#, VB, C++, J#, etc.

Page 14: Introduction to Programming in C# John Galletly. The Basics.

C# Introduction

Page 15: Introduction to Programming in C# John Galletly. The Basics.

Class

The class is the basic unit in C#.

Every executable C# statement must be placed inside a class.

Every C# program must have at least one one class, and one method called Main() in that class.

A class is just a template or blueprint for defining objects.

Page 16: Introduction to Programming in C# John Galletly. The Basics.

Basic syntax for class declaration

Class comprises a class header and class body.

class class_name{

class body }

Note: No semicolon (;) to terminate class block.

But statements must be terminated with a semicolon ;

Class body comprises class members – constructor, data fields and methods.

Page 17: Introduction to Programming in C# John Galletly. The Basics.

The Method Main

• Every C# application must have a method named Main()defined in one of its classes.

– It does not matter which class contains the method - you can have as many classes as you want in a given application - as long as one class has a method named Main.

• The Main method must be defined as static.

– The static keyword tells the compiler that the Main method is a global method, and that the class does not need to be instantiated for the method to be called.

- May also include the access modifier public

Page 18: Introduction to Programming in C# John Galletly. The Basics.

Syntax for simple C# program

// Program start class class class_name { // Main begins program execution public static void Main(string[] args) {

statements } }

A C# program starts with a class which encapsulates themethod Main()

Note: Main() – not main()

Programmer-defined class name

May be replaced by Main()

Page 19: Introduction to Programming in C# John Galletly. The Basics.

Simple C# program

// Program start class class HelloWorld { // Main begins program execution static void Main() { System.Console.WriteLine("Hello World"); } }

Page 20: Introduction to Programming in C# John Galletly. The Basics.

using System;

class HelloWorld{ static void Main() { Console.WriteLine("Hello World!"); }}

Include the standard namespace "System"

Define a class called "HelloWorld"

Define the Main() method – the program entry point

Write text message on the screen by calling the method "WriteLine" of the class "Console"

Page 21: Introduction to Programming in C# John Galletly. The Basics.

To access classes and methods without using their fully qualified name, use the using directive.

Example using System; Instead of writing

System.Console.WriteLine()

May write

using System;

Console.WriteLine()

Page 22: Introduction to Programming in C# John Galletly. The Basics.

Using namespaces

// Namespace Declarationusing System;

// Program start class public class HelloWorld { // Main begins program execution static void Main() { // This is a single line comment

/* This is a multiple line comment */

Console.WriteLine("Hello World!"); } }

Page 23: Introduction to Programming in C# John Galletly. The Basics.

Operators, Types, and Variables

Variables

C# is a strongly “typed" language (aka “type-safe”.)

- All operations on variables are performed with consideration of what the variable's “type" is.

There are rules that define what operations are legal in order to maintain the integrity of the data you put in a variable.

Page 24: Introduction to Programming in C# John Galletly. The Basics.

Types

C# simple types consist of the Boolean type and three numeric types (integer, floating-point and decimal) and the String type.

The pre-defined reference types are object and string, where object is the ultimate base class of all other types.

Boolean type - Boolean types are declared using the keyword, bool. They have two values: true or false.These are keywords.

E.g. bool gaga = true;

Page 25: Introduction to Programming in C# John Galletly. The Basics.

Data Types

• Common C# data types

– The “root” type object– Logical bool– Signed Integer short, int, long– Unsigned Integer ushort, uint, ulong– Floating-point float, double, – Text char, string

Page 26: Introduction to Programming in C# John Galletly. The Basics.

The Object Type

• The object type:– Is declared by the object keyword– Is the base type of all other types– Can hold values of any type

object dataContainer = 5;Console.Write("The value of dataContainer is: ");Console.WriteLine(dataContainer);

dataContainer = "Five"; // same variableConsole.Write("The value of dataContainer is: ");Console.WriteLine(dataContainer);

Page 27: Introduction to Programming in C# John Galletly. The Basics.

All types are compatible with object

- A variable of any type can be assigned to variables of type object

- All operations of type object are applicable to variables of any type.

Page 28: Introduction to Programming in C# John Galletly. The Basics.

Types, Classes, and Objects

• Data Type

– C# has more than one type of number

• int type is a whole number

• Floating-point types can have a fractional portion

• Types are actually implemented through classes

– One-to-one correspondence between a class and a type

– Simple data type such as int is implemented as a class

Page 29: Introduction to Programming in C# John Galletly. The Basics.

Integer type

In C#, an integer is a category of types. They are whole numbers, either signed or unsigned.

Page 30: Introduction to Programming in C# John Galletly. The Basics.

Floating-Point and Decimal Types

A C# floating-point type is either a float or double. They are used any time you need to represent a real number.

The decimal type should be used when representing financial or money values.

Page 31: Introduction to Programming in C# John Galletly. The Basics.

Caution with Floating-Point Comparisons

• Sometimes problems can happen when comparing floating-point number values due to rounding errors.– Comparing floating-point numbers should not be made directly

with the == (equality) operator

• Example:

double a = 1.0;double b = 0.33;double sum = 1.33;

bool equal = (a+b == sum); // Not necessarily true!

Console.WriteLine("a+b={0} sum={1} equal={2}", a+b, sum, equal);

This strange syntax will be explained shortly!

Page 32: Introduction to Programming in C# John Galletly. The Basics.

int studentCount; // number of students in the class

int ageOfStudent = 20; // age - originally initialized to 20

int numberOfExams; // number of exams

int coursesEnrolled; // number of courses enrolled

double extraPerson = 3.50; // extraPerson originally set // to 3.50double averageScore = 70.0; // averageScore originally set // to 70.0double priceOfTicket; // cost of a movie ticketdouble gradePointAverage; // grade point averagefloat totalAmount = 23.57f; // note the f must be placed after

// the value for float types

Page 33: Introduction to Programming in C# John Galletly. The Basics.

Example

• An example of using types in C#– Declare before you use (compiler enforced)– Initialize before you use (compiler enforced)

public class App{ public static void Main() { int width, height; width = 2; height = 4;

int area = width * height;

int x; int y = x * 2; ... }}

declarations

declaration + initializer

error, x not set

Page 34: Introduction to Programming in C# John Galletly. The Basics.

Boolean Variables

• Based on true/false• Boolean type in C# → bool• Does not accept integer values such as 0, 1, or -1

bool undergraduateStudent; bool moreData = true;

Page 35: Introduction to Programming in C# John Galletly. The Basics.

Boolean Values – Example

• Example of boolean variables taking values of true or false:

int a = 1;int b = 2;

bool greaterAB = (a > b);

Console.WriteLine(greaterAB); // False

bool equalA1 = (a == 1);

Console.WriteLine(equalA1); // True

Page 36: Introduction to Programming in C# John Galletly. The Basics.

The character data type:

- Represents symbolic information – single quotes ‘… ‘

- Is declared by the char keyword

- Gives each symbol a corresponding integer code

- Has a '\0' default value

Data Type char

Page 37: Introduction to Programming in C# John Galletly. The Basics.

The String Data Type

• The string data type:– Represents a sequence of characters– Is declared by the string keyword– Has a default value null (no value)– Really a pre-defined class

• Strings are enclosed in double quotes: “…”

• Strings can be concatenated– Using the + operator

string s = “SWU – “ + “ICoSCIS Project";

Page 38: Introduction to Programming in C# John Galletly. The Basics.

Saying Hello – Example

• Concatenating the two names of a person to obtain his full name using +

string firstName = "Ivan";string lastName = "Ivanov";Console.WriteLine("Hello, {0}!\n", firstName);

string fullName = firstName + " " + lastName;Console.WriteLine("Your full name is {0}.", fullName);

Page 39: Introduction to Programming in C# John Galletly. The Basics.

Class System.String

Can be used as standard type stringstring s = “ICoSCIS";

Note• Can be concatenated with +: “SWU " + s;

• Can be indexed: s[i]

• String length: s.Length

• String values can be compared with == and !=: if (s == “SWU") ...

• Class String defines many useful operations:CompareTo, IndexOf, StartsWith,

Substring, ...

Page 40: Introduction to Programming in C# John Galletly. The Basics.

Data Constants

• Add the keyword const to a declaration• Value cannot be changed • Standard naming convention – identifier usually

uppercase charactersSyntax

const type identifier = expression;

Exampleconst double TAX_RATE = 0.0675; const int SPEED = 70;const char HIGHEST_GRADE = ‘A’;

Page 41: Introduction to Programming in C# John Galletly. The Basics.
Page 42: Introduction to Programming in C# John Galletly. The Basics.
Page 43: Introduction to Programming in C# John Galletly. The Basics.

Mixed Expressions – Different Types

• Explicit type coercion– Cast

Syntax: (type) expression

examAverage = (exam1 + exam2 + exam3) / (double) count;

int value1 = 0, anotherNumber = 75;

double value2 = 100.99, anotherDouble = 100;

value1 = (int) value2; // value1 = 100 value2 = (double) anotherNumber; // value2 = 75.0

Page 44: Introduction to Programming in C# John Galletly. The Basics.

Identifiers

• Identifiers may consist of– Letters – Digits [0-9]– Underscore "_"

• Identifiers– Can begin only with a letter or an underscore– Cannot be a C# keyword

Page 45: Introduction to Programming in C# John Galletly. The Basics.

Identifiers – Examples

• Examples of correct identifiers:

• Examples of incorrect identifiers:

int new; // new is a keywordint 2Pac; // Cannot begin with a digit

int New = 2; // Here N is capitalint _2Pac; // This identifier begins with _

string greeting = "Hello";

int n = 100; // Undescriptiveint numberOfClients = 100; // Descriptive

// Overdescriptive identifier:int numberOfPrivateClientOfTheFirm = 100;

Page 46: Introduction to Programming in C# John Galletly. The Basics.

Initializing Variables

• Initializing

– Must be done before the variable is used!

• Several ways of initializing:

– By using the new keyword

– By using a literal expression

– By assigning an already initialized variable

Page 47: Introduction to Programming in C# John Galletly. The Basics.

Initialization – Examples

• Example of some initializations:

// The following would assign the default// value of the int type to num:int num = new int(); // num = 0

// This is how we use a literal expression:float heightInMeters = 1.74f;

// Here we use an already initialized variable:string greeting = "Hello World!";string message = greeting;

Page 48: Introduction to Programming in C# John Galletly. The Basics.

int numberOfMinutes, count, minIntValue;char firstInitial, yearInSchool, punctuation;

numberOfMinutes = 45;count = 0;minIntValue = -2147483648;firstInitial = ‘B’; yearInSchool = ‘1’;enterKey = ‘\n’; // newline escape character

Page 49: Introduction to Programming in C# John Galletly. The Basics.

Statements in C#

• C# supports the standard assortment …

• assignment• function• conditional– if, if-else, switch

• iteration– for, while, do-while

• control flow– return, break, continue

Page 50: Introduction to Programming in C# John Galletly. The Basics.

Console Input/Output Methods

Writing to screen

Methods are members of Console class

Console.WriteLine()

- Writes to screen followed by newline

Console.Write( )

- Writes to screen without newline

Page 51: Introduction to Programming in C# John Galletly. The Basics.

• Console.Read( ) reads a single character from the keyboard

• Console.ReadLine( ) reads a string of characters from the keyboard – Until the enter key is pressed– Character string has type string– Must use a conversion method to convert the input string

to the proper type!

Reading from keyboard

Page 52: Introduction to Programming in C# John Galletly. The Basics.

Console.Write(…)

int a = 15;...Console.Write(a); // 15 – next print stays on same line

Printing a variable

Page 53: Introduction to Programming in C# John Galletly. The Basics.

• Printing using a formatting string

double a = 15.5;int b = 14;...Console.Write("{0} + {1} = {2}", a, b, a + b);// 15.5 + 14 = 29.5

Page 54: Introduction to Programming in C# John Galletly. The Basics.

Example

Console.Write("{0} + {1} = {2}", a, b, a + b);

Formatting string:

"{0} + {1} = {2}“

The numbers refer to the three variables a, b, a + b

The numbers are “placeholders” for the variables.

The numbers start from 0. 0 – a1 – b2 – a + b

Formatting String

Page 55: Introduction to Programming in C# John Galletly. The Basics.

Console.WriteLine(…)

Printing more than one variable using a formatting string

string str = "Hello C#!";...Console.WriteLine(str);

Printing a string variable

string name = “Elena";int year = 1980;...Console.WriteLine("{0} was born in {1}.", name, year);// Elena was born in 1980.

Next printing will start from the new line

Page 56: Introduction to Programming in C# John Galletly. The Basics.

Reading Numeric Types

• Numeric types can not be read directly from the console• To read a numeric type, do the following:

1. Read a string value2. Convert it to the required numeric typeExample

int.Parse(string)– Converts a string to int

string str = Console.ReadLine()int number = int.Parse(str);

Console.WriteLine("You entered: ", number);

Page 57: Introduction to Programming in C# John Galletly. The Basics.

Converting Strings to Numbers

• Types have a method Parse() for extracting the numeric value from a string– double.Parse(string ) – int.Parse(string ) – char.Parse(string ) – bool.Parse(string )

• Expects string argument– Argument must be a number – string format

• Returns the number (or char or bool)

Page 58: Introduction to Programming in C# John Galletly. The Basics.

Example

public static void Main(){ int a = int.Parse(Console.ReadLine()); int b = int.Parse(Console.ReadLine());

Console.WriteLine("{0} + {1} = {2}", a, b, a+b); Console.WriteLine("{0} * {1} = {2}", a, b, a*b);

float f = float.Parse(Console.ReadLine()); Console.WriteLine("{0} * {1} / {2} = {3}", a, b, f, a*b/f);}

Page 59: Introduction to Programming in C# John Galletly. The Basics.

using System; class SquareInputValue { static void Main( ) { string inputStringValue; double aValue, result; Console.Write(“Enter a value to be squared: ”); inputStringValue = Console.ReadLine( ); aValue = double.Parse(inputStringValue); result = Math.Pow(aValue, 2); Console.WriteLine(“{0} squared is {1}”, aValue, result); } }