10
2006 Summer - C# Tutorial 1 C# Tutorial Jonas Tan [email protected]

(02) c sharp_tutorial

Embed Size (px)

DESCRIPTION

 

Citation preview

Page 1: (02) c sharp_tutorial

2006 Summer - C# Tutorial 1

C# Tutorial

Jonas Tan

[email protected]

Page 2: (02) c sharp_tutorial

2006 Summer - C# Tutorial 2

Reference

• MSDN The C# Language– http://msdn.microsoft.com/vcsharp/programming/language/

Page 3: (02) c sharp_tutorial

2006 Summer - C# Tutorial 3

Hello World!using System;

class Form1{

private System.Windows.Forms.TextBox textBox1;

//Constructorpublic Form1() {

textbox1 = “Hello world!";}

//Start the programstatic void Main() {

Application.Run( new Form1() ); }}

Page 4: (02) c sharp_tutorial

2006 Summer - C# Tutorial 4

Type System

• Value Types:– byte b = 120 (8-bit)– char c = ‘a’; (16-bit Unicode)– int i=7; (32-bit)– long l = 88; (64-bit)– string s = “a string”; (set of Unicode characters)

• Reference Types (arrays)– string[] s = new string[10];– int[] i = new int[5];– char[] c = new char[16];– byte[] b = new byte[22];

Page 5: (02) c sharp_tutorial

2006 Summer - C# Tutorial 5

Indexers

• string s = “this is a string”;

• char ch = s[3];

• s[6] = ‘x’; //Error! Read Only.

• int[] i = new int[] {2, 4, 6, 8, 10};

• int b = i[2];

• i[3] = 98;

Page 6: (02) c sharp_tutorial

2006 Summer - C# Tutorial 6

Basic Type casting

• int (32-bit) to long (64-bit)int a = 537;long b = 6473291;b = (long)a;

• char(16-bit) to int(32-bit)char c = ‘x’;int d = 8;d = (int)c;

• Dangerous Casting– cast int to uint (possible sign error)– long to short (possible overflow)

Page 7: (02) c sharp_tutorial

2006 Summer - C# Tutorial 7

Advanced Type Casting

• int to stringint a = 3;string s1 = a.ToString();

• char array to stringchar [ ] b2 = new char[3] {‘a’, ‘c’, ‘e’, ‘g’, ‘h’};String s2 = new string(b2);

• string to intsting s3 = “564”;int c = int.Parse(s3);

• string to byte arraybyte[ ] buf1 = Encoding.Unicode.GetBytes(s3);

• string to char arraychar [ ] buf2 = s3.ToCharArray();

Page 8: (02) c sharp_tutorial

2006 Summer - C# Tutorial 8

Operators

• +, -, *, /, %

• ++, --

• ==, !=, <, >, <=, >=

• &, |, ^, ~, !

• true, false

Page 9: (02) c sharp_tutorial

2006 Summer - C# Tutorial 9

Shift Operation

• Use two unsigned integers to simulate a unsigned long integer

ulong ul = 73654823; //64-bit

uint a[2] = new uint[]{0,0}; //2 32-bit unsigned integers

a[0] = (uint) ul;

a[1] = (uint) ul >> 32;

Page 10: (02) c sharp_tutorial

2006 Summer - C# Tutorial 10

if and while statements• if( x>3 && x<8 )

{…

}

• while( i>2 ) {

…}

• for( int i=0; i<x; ++i ) {

…}