BIM313 – Advanced Programming Techniques C# Basics 1.

Post on 11-Jan-2016

234 views 5 download

Tags:

transcript

BIM313 – Advanced Programming Techniques

C# Basics

1

Contents

• Variables and Expressions– Comments– Variables– Expressions– Operators– Namespaces

• Flow Control– if, switch– while, do-while, for, foreach– Binary operators

2

Basic C# Syntax

• White spaces (space, carriage return, tab) are ignored by the C# compiler

• Statements are terminated with a semicolon (;)• C# code is case-sensitive• C# is a block-structured language and blocks are

delimited with curly brackets (‘{’ and ‘}’)• Please indent your code so that your code

becomes more readable• Write comments while writing the codes

3

Comments• Type I/* Single line comment *//* Multi- Line Comment */

• Type II// Another single line commenta = 0; // Initialize the count

• Type III/// Special comments used for documentation

4

Variables

• Think variables as boxes to store data in them• Variables have types, names, and values

int num = 5;• Here, int is the type, num is the name, and 5 is

the value of the variable• All variables should be declared before using

them

5

Simple Types

• Simple types include types such as numbers and Boolean (true or false) values

• There are several types to represent numbers, because different amount of bytes are required for each type

6

Integer TypesType Alias for Allowed Values # of bytes

sbyte System.SByte Integer between –128 and 127 1

byte System.Byte Integer between 0 and 255 1

short System.Int16 Integer between –32768 to 32767 2

ushort System.UInt16 Integer between 0 and 65535 2

int System.Int32 Integer between –2,147,483,648 and 2,147,483,647 4

uint System.UInt32 Integer between 0 and 4,294,967,295 4

long System.Int64 Integer between –9223372036854775808 and 9223372036854775807 8

ulong System.UInt64 Integer between 0 and 18446744073709551615 8

7u: unsigned s: signed

Floating-Point Value TypesType Alias for Range # of bytes

float System.Single 4

double System.Double 8

decimal System.Decimal 16

8

PrecisionsType Precision

float 7-8 digits

double 15-16 digits

decimal 28 digits

9

The decimal value type is generally used in currencies which require more precision!

Other Simple TypesType Alias for Allowed Values

char System.Char Single Unicode character, stored as an integer between 0 and 65535

bool System.Boolean true or false

string System.String A sequence of characters

10

Note that char type is stored in 2 bytes and it is

Unicode!

Variable Declaration, Assignment, and Printing Example

static void Main(string[] args){

int myInteger;string myString;myInteger = 17;myString = "\"myInteger\" is";Console.WriteLine("{0} {1}.", myString, myInteger);

}

11

Two variables aredeclared here

Values are assignedto the variables

Variables are displayed on the screen.

"myInteger" is 17.

Printing Variable Values

• Use Console.Write() or Console.WriteLine() methods to display variable values on the screen

• Console.WriteLine() method adds a new line at the end of the line

• The methods have several faces to print several types; use the most suitable one

12

Some Console.WriteLine() Faces

13

Printing an int on the screen

• int x = 17, y = 25;• Console.WriteLine(x);• Console.WriteLine(x.ToString());• Console.Write(“x = ”);• Console.WriteLine(x);• Console.WriteLine(“x = ” + x);• Console.WriteLine(“x = ” + x.ToString());• Console.WriteLine(“x = {0}, y = {1}.”, x, y);

14

1717x = 17x = 17x = 17x = 17, y = 25.

Variable Naming

• The first character must be either a letter, or an underscore character (_)

• Subsequent characters may be letters, underscore character, or numbers.

• Reserved words can’t be used as variable names– If you want a reserved word as variable name, you can put an at character (@) at the beginning

15

Example: Valid Variable Names

• myBigVar• VAR1• _test• i• myVariable• MyVariable• MYVARIABLE

16

Example: Invalid Variable Names

• a+b• 99bottles• namespace• double• my-result

17

Keywordsabstract const extern int out short typeof

as continue false interface override sizeof uint

base decimal finally internal params stackalloc ulong

bool default fixed is private static unchecked

break delegate float lock protected string unsafe

byte do for long public struct ushort

case double foreach namespace readonly switch using

catch else goto new ref this virtual

char enum if null return throw void

checked event implicit object sbyte true volatile

class explicit in operator sealed try while

18

C# Contextual Keywordsadd ascending async await by descending dynamic

equals from get global group in into

join let on orderby partial remove select

set value var where yield

19

Contextual keyword are used in certain language constructs. They can’t be used as identifier in those constructs. Otherwise,

they can be used as identifiers.

Variable Naming Conventions

• Hungarian Notation• Camel Case• Pascal Case

20

Hungarian Notation

• Place a lowercase prefix which shows the type of the variable– nAge– iAge– fDelimeter– btnClick– txtName

21

Camel Case

• Begin first word with lowercase, others with uppercase– age– firstName– lastName– birthDay

22

Pascal Case

• Start all words with uppercase letters– Age– FirstName– LastName– WinterOfDiscontent

23

Escape SequencesEscape Sequence Character Produced Unicode Value

\’ Single quotation mark 0x0027

\” Double quotation mark 0x0022

\\ Backslash 0x005C

\0 Null 0x0000

\a Alert (causes a beep) 0x0007

\b Backspace 0x0008

\f Form feed 0x000C

\n New line 0x000A

\r Carriage return 0x000D

\t Horizontal tab 0x0009

\v Vertical tab 0x000B

24

More About Strings…

• You can use Unicode values after \u– “Karli\’s string”– “Karli\u0027s string”

• If you place the @ character before a string, all escape sequences are ignored.– “C:\\inetpub\\wwwroot\\”– @“C:\inetpub\wwwroot\”– “A short list:\nitem 1\nitem 2”– @“A short list:

item 1item 2”

25

Variable Declaration and Assignment

• int age;• age = 25;• int age = 25;• int xSize, ySize;• int xSize = 4, ySize = 5;• int xSize, ySize = 5;

26

Operators

• Addition, subtraction, etc. are made using operators

• Three types of operators:– Unary – Act on single operand– Binary – Act on two operands– Tertiary – Act on three operands

27

Mathematical OperatorsOperator Category Example

+ Binary var1 = var2 + var3;

– Binary var1 = var2 – var3;

* Binary var1 = var2 * var3;

/ Binary var1 = var2 / var3;

% Binary var1 = var2 % var3;

+ Unary var1 = +var2;

– Unary var1 = –var2;

28

% : Remainder operatorExample: 8 % 3 gives 2.

Increment and Decrement Operators

Operator Category Example

++ Unary var1 = ++var2;

-- Unary var1 = --var2;

++ Unary var1 = var2++;

-- Unary var1 = var2--;

29

Increment first,assign next

Assign first,increment next

Exercise

int var1, var2 = 5, var3 = 6;var1 = var2++ * --var3;Console.WriteLine("var1={0}, var2={1}, var3={2}", var1, var2, var3);

30

How?

Printing Variable Values

int var1 = 3, var2 = 5;Console.WriteLine("var1 = {0}, var2 = {1}", var1, var2);

31

var1 = 3, var2 = 5

Printing Variable Values

int var1 = 3, var2 = 5;Console.WriteLine("{0}{1}{0}{1}{1}", var1, var2);

32

35355

Reading Strings

string userName;Console.Write("Your name: ");userName = Console.ReadLine();Console.WriteLine("Welcome {0}!", userName);

33

Your name: MuzafferWelcome Muzaffer!

Reading Integers

• int age;• Console.WriteLine("Your age: ");• age = int.Parse(Console.ReadLine());• Console.WriteLine("Your age is {0}.", age);

34

Equivalent code:Convert.ToInt32(Console.ReadLine());

Reading Doubles

• double w;• Console.WriteLine("Your weight (in kg.): ");• w = double.Parse(Console.ReadLine());• Console.WriteLine("You weigh {0} kg.", w);

35

Equivalent code:Convert.ToDouble(Console.ReadLine());

Assignment OperatorsOperator Example Equivalent

= var1 = var2;

+= var1 += var2; var1 = var1 + var2;

-= var1 -= var2; var1 = var1 – var2;

*= var1 *= var2; var1 = var1 * var2;

/= var1 /= var2; var1 = var1 / var2;

%= var1 %= var2; var1 = var1 % var2;

36

Operator PrecedencePrecedence Operators

Highest ++, -- (used as prefixes), +, - (unary)

*, /, %

+, -

=, *=, /=, %=, +=, -=

Lowest ++, -- (used as suffixes)

37

Namespaces

• .NET way of providing containers– Header files in C and C++– Packages in Java

• .NET classes are grouped in namespaces– Sin, Cos, Atan, Acos, Pi, Sqrt, etc. in Math namespace– Int32, Double, etc. in System namespace– Windows Forms classes in System.Windows.Forms– Registry operations in Microsoft namespace

• You also can write your programs or DLLs in a separate namespace, e.g. using your company name

38

Flow Control

• Branching (if, switch, ternary operator)• Looping (for, while, do-while, foreach)

39

Comparison OperatorsOperator Meaning

== equal to

!= not equal to

< less than

> greater than

<= less than or equal to

>= greater than or equal to

40

Boolean Variables

• A Boolean variable may take values true or false– bool isWhite = true;– isWhite = false;

• Comparison results can be stored in Boolean variables– bool isLong = (height > 195);– bool isWhite = (color == Color.White);

41

Fundamental Logical OperatorsOperator Name Example

&& AND (a > 0) && (a < 10)

|| OR (a <= 0) || (a >= 10)

! NOT !(a < 100)

42

The ‘if’ Statement

int height;Console.Write("Enter your height (in cm.) ");height = int.Parse(Console.ReadLine());if (height > 190) Console.WriteLine("You are a tall person!");else Console.WriteLine("Your height is normal!");

43

if Statement

if (expression) <statement to execute when expression is true>;

if (expression){ <statement 1>; <statement 2>;}

44

if..else

if (expression) <statement to execute when expression is true>;else <statement to execute when expression is false>;

• If there are more statements, use curly brackets.

45

Some Notes on ‘if’

• Parentheses are required, they can’t be omitted• Curly braces (‘{’ and ‘}’)should be used if there are

more than one statements:if (test){ statement1; statement2;}

• else part can be omitted• if statements can be nested

46

Example: Finding the smallest of 3 integers

int a, b, c, min;Console.WriteLine("Enter 3 integers:");Console.Write("a = ");a = int.Parse(Console.ReadLine());Console.Write("b = ");b = int.Parse(Console.ReadLine());Console.Write("c = ");c = int.Parse(Console.ReadLine());

if (a < b){ if (a < c) min = a; else

min = c;}else{ if (b < c) min = b; else min = c;}

Console.WriteLine("The smallest one is {0}.", min);

47

Checking Conditionsif (var1 == 1) { // Do something.}else { if (var1 == 2) { // Do something else. } else { if (var1 == 3 || var1 == 4) { // Do something else. } else { // Do something else. } }

}

if (var1 == 1) { // Do something.}else if (var1 == 2) { // Do something else.}else if (var1 == 3 || var1 == 4) { // Do something else.}else { // Do something else.}

48

Common Mistakes

• if (var1 = 1) {…}• if (var1 == 1 || 2) {…}

49

The ‘switch’ Statementswitch (<testVar>){ case <comparisonVal1>: <code to execute if <testVar> == <comparisonVal1> > break; case <comparisonVal2>: <code to execute if <testVar> == <comparisonVal2> > break; . . . case <comparisonValN>: <code to execute if <testVar> == <comparisonValN> > break; default: <code to execute if <testVar> != comparisonVals> break;}

50

Example 1switch (var1){ case 1: // Do something. break; case 2: // Do something else. break; case 3: case 4: // Do something else. break; default: // Do something else. break;}

51

Example 2switch (option){ case 1: Console.WriteLine(“You select 1”); break; case 2: Console.WriteLine(“You select 2”); break; case 3: Console.WriteLine(“You select 3”); break; default: Console.WriteLine(“Please select an integer between 1 and 3.”); break;}

52

switch Exampleswitch (strProfession){ case "teacher": MessageBox.Show("You educate our young"); break; case "programmer": MessageBox.Show("You are most likely a geek"); break; case "accountant": MessageBox.Show("You are a bean counter"); break; default: MessageBox.Show("Profession not found in switch statement"); break;}

53

In C, only integer values can be used as the expression but in

C#, strings can be used too.

Don’t forget to use breaks!

Example 3switch (strAnimal){ case “bird”: Console.WriteLine(“It has 2 legs.”); break; case “horse”: case “dog”: case “cat”: Console.WriteLine(“It has 4 legs.”); break; case “centipede”: Console.WriteLine(“It has 40 legs.”); break; case “snake”: Console.WriteLine(“It has no legs.”); break; default: Console.WriteLine(“I don’t know that animal!”); break;} 54

The Ternary Operator

• ? :• <test> ? <resultIfTrue> : <resultIfFalse>• Tertiary operator because it acts on 3

operands (remember unary and binary operators acting on 1 and 2 operands resp.)

• Example:– if (a < b) min = a; else min = b;– min = (a < b) ? a : b;

55

Looping

56

for Loop

for (initializers; check_condition; modifying_expressions){ <statements>}• Example:for (i = 0; i < 10; i++) { Console.WriteLine("i = " + i.ToString());}

57

while Loop

while (expression){ <statements>}

58

do-while Loop

do{ <statements>} while (expression);

59

foreach Loop

foreach (<type> <name> in <list>){ <statements>}

60

Displaying Months using for Loop

string[] months = new string[] { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };

for (int i = 0; i < months.Length; i++){ MessageBox.Show(months[i]);}

61

Displaying Months using foreach

string[] months = new string[] { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };

foreach (string month in months){ MessageBox.Show(month);}

62

Exercise

• Display first ten prime numbers.

63

Interrupting Loops

• break – ends the loop immediately• continue – ends the current loop cycle• return – jumps out of the function• goto – jumps to the specified location (don’t use)

64

Infinite Loops

while (true){ …}

65

Exampleint num;while (true){ Console.Write(“Enter a number between 1 and 100: ”); num = Convert.ToInt32(Console.ReadLine()); if (num >= 1 && num <= 100) break; else { Console.WriteLine(“It should be between 1 and 100.”); Console.WriteLine(“Please try again!\n”); }}

66

Bitwise Operators

• & (Bitwise AND)• | (Bitwise OR)• ~ (Bitwise NOT)• ^ (Bitwise XOR)

67

Examples

• 0110 & 0101 = 0100 (1&1=1, otherwise 0)• 0110 | 0101 = 0111 (0|0=0, otherwise 1)• 0110 ^ 0101 = 0011 (same0, different1)• ~0110 = 1001 (01, 10)

68

Examples

option = Location.Left | Location.Bottom;

if (option & Location.Left != 0) MessageBox.Show(“Indented to left.”);if (option & Location.Bottom != 0) MessageBox.Show(“Indented to right.”);

69

Shift Operators

• >> (Shift right)• << (Shift left)• >>=• <<=

70

Examples

• int a = 16;• int b = a >> 2; // b becomes 4• int c = a << 4; // c becomes 256• a >>= 2; // a becomes 4• a <<= 4; // a becomes 64

71