+ All Categories
Home > Documents > BIM313 – Advanced Programming Techniques C# Basics 1.

BIM313 – Advanced Programming Techniques C# Basics 1.

Date post: 11-Jan-2016
Category:
Upload: phillip-harold-bell
View: 234 times
Download: 5 times
Share this document with a friend
Popular Tags:
71
BIM313 – Advanced Programming Techniques C# Basics 1
Transcript
Page 1: BIM313 – Advanced Programming Techniques C# Basics 1.

BIM313 – Advanced Programming Techniques

C# Basics

1

Page 2: 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

Page 3: BIM313 – Advanced Programming Techniques C# Basics 1.

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

Page 4: BIM313 – Advanced Programming Techniques C# Basics 1.

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

Page 5: BIM313 – Advanced Programming Techniques C# Basics 1.

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

Page 6: BIM313 – Advanced Programming Techniques C# Basics 1.

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

Page 7: BIM313 – Advanced Programming Techniques C# Basics 1.

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

Page 8: BIM313 – Advanced Programming Techniques C# Basics 1.

Floating-Point Value TypesType Alias for Range # of bytes

float System.Single 4

double System.Double 8

decimal System.Decimal 16

8

Page 9: BIM313 – Advanced Programming Techniques C# Basics 1.

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!

Page 10: BIM313 – Advanced Programming Techniques C# Basics 1.

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!

Page 11: BIM313 – Advanced Programming Techniques C# Basics 1.

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.

Page 12: BIM313 – Advanced Programming Techniques C# Basics 1.

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

Page 13: BIM313 – Advanced Programming Techniques C# Basics 1.

Some Console.WriteLine() Faces

13

Page 14: BIM313 – Advanced Programming Techniques C# Basics 1.

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.

Page 15: BIM313 – Advanced Programming Techniques C# Basics 1.

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

Page 16: BIM313 – Advanced Programming Techniques C# Basics 1.

Example: Valid Variable Names

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

16

Page 17: BIM313 – Advanced Programming Techniques C# Basics 1.

Example: Invalid Variable Names

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

17

Page 18: BIM313 – Advanced Programming Techniques C# Basics 1.

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

Page 19: BIM313 – Advanced Programming Techniques C# Basics 1.

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.

Page 20: BIM313 – Advanced Programming Techniques C# Basics 1.

Variable Naming Conventions

• Hungarian Notation• Camel Case• Pascal Case

20

Page 21: BIM313 – Advanced Programming Techniques C# Basics 1.

Hungarian Notation

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

21

Page 22: BIM313 – Advanced Programming Techniques C# Basics 1.

Camel Case

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

22

Page 23: BIM313 – Advanced Programming Techniques C# Basics 1.

Pascal Case

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

23

Page 24: BIM313 – Advanced Programming Techniques C# Basics 1.

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

Page 25: BIM313 – Advanced Programming Techniques C# Basics 1.

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

Page 26: BIM313 – Advanced Programming Techniques C# Basics 1.

Variable Declaration and Assignment

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

26

Page 27: BIM313 – Advanced Programming Techniques C# Basics 1.

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

Page 28: BIM313 – Advanced Programming Techniques C# Basics 1.

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.

Page 29: BIM313 – Advanced Programming Techniques C# Basics 1.

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

Page 30: BIM313 – Advanced Programming Techniques C# Basics 1.

Exercise

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

30

How?

Page 31: BIM313 – Advanced Programming Techniques C# Basics 1.

Printing Variable Values

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

31

var1 = 3, var2 = 5

Page 32: BIM313 – Advanced Programming Techniques C# Basics 1.

Printing Variable Values

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

32

35355

Page 33: BIM313 – Advanced Programming Techniques C# Basics 1.

Reading Strings

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

33

Your name: MuzafferWelcome Muzaffer!

Page 34: BIM313 – Advanced Programming Techniques C# Basics 1.

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());

Page 35: BIM313 – Advanced Programming Techniques C# Basics 1.

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());

Page 36: BIM313 – Advanced Programming Techniques C# Basics 1.

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

Page 37: BIM313 – Advanced Programming Techniques C# Basics 1.

Operator PrecedencePrecedence Operators

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

*, /, %

+, -

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

Lowest ++, -- (used as suffixes)

37

Page 38: BIM313 – Advanced Programming Techniques C# Basics 1.

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

Page 39: BIM313 – Advanced Programming Techniques C# Basics 1.

Flow Control

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

39

Page 40: BIM313 – Advanced Programming Techniques C# Basics 1.

Comparison OperatorsOperator Meaning

== equal to

!= not equal to

< less than

> greater than

<= less than or equal to

>= greater than or equal to

40

Page 41: BIM313 – Advanced Programming Techniques C# Basics 1.

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

Page 42: BIM313 – Advanced Programming Techniques C# Basics 1.

Fundamental Logical OperatorsOperator Name Example

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

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

! NOT !(a < 100)

42

Page 43: BIM313 – Advanced Programming Techniques C# Basics 1.

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

Page 44: BIM313 – Advanced Programming Techniques C# Basics 1.

if Statement

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

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

44

Page 45: BIM313 – Advanced Programming Techniques C# Basics 1.

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

Page 46: BIM313 – Advanced Programming Techniques C# Basics 1.

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

Page 47: BIM313 – Advanced Programming Techniques C# Basics 1.

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

Page 48: BIM313 – Advanced Programming Techniques C# Basics 1.

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

Page 49: BIM313 – Advanced Programming Techniques C# Basics 1.

Common Mistakes

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

49

Page 50: BIM313 – Advanced Programming Techniques C# Basics 1.

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

Page 51: BIM313 – Advanced Programming Techniques C# Basics 1.

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

Page 52: BIM313 – Advanced Programming Techniques C# Basics 1.

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

Page 53: BIM313 – Advanced Programming Techniques C# Basics 1.

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!

Page 54: BIM313 – Advanced Programming Techniques C# Basics 1.

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

Page 55: BIM313 – Advanced Programming Techniques C# Basics 1.

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

Page 56: BIM313 – Advanced Programming Techniques C# Basics 1.

Looping

56

Page 57: BIM313 – Advanced Programming Techniques C# Basics 1.

for Loop

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

57

Page 58: BIM313 – Advanced Programming Techniques C# Basics 1.

while Loop

while (expression){ <statements>}

58

Page 59: BIM313 – Advanced Programming Techniques C# Basics 1.

do-while Loop

do{ <statements>} while (expression);

59

Page 60: BIM313 – Advanced Programming Techniques C# Basics 1.

foreach Loop

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

60

Page 61: BIM313 – Advanced Programming Techniques C# Basics 1.

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

Page 62: BIM313 – Advanced Programming Techniques C# Basics 1.

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

Page 63: BIM313 – Advanced Programming Techniques C# Basics 1.

Exercise

• Display first ten prime numbers.

63

Page 64: BIM313 – Advanced Programming Techniques C# Basics 1.

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

Page 65: BIM313 – Advanced Programming Techniques C# Basics 1.

Infinite Loops

while (true){ …}

65

Page 66: BIM313 – Advanced Programming Techniques C# Basics 1.

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

Page 67: BIM313 – Advanced Programming Techniques C# Basics 1.

Bitwise Operators

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

67

Page 68: BIM313 – Advanced Programming Techniques C# Basics 1.

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

Page 69: BIM313 – Advanced Programming Techniques C# Basics 1.

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

Page 70: BIM313 – Advanced Programming Techniques C# Basics 1.

Shift Operators

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

70

Page 71: BIM313 – Advanced Programming Techniques C# Basics 1.

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


Recommended