You are on page 1of 111

Chng 2 C# Language Fundamentals

Ni dung
Cach vit 1 console application
Console I/0 va lnh nhp xut

Khai bao bin:


Strongly type Implicited type local variable

Cac kiu d liu


Value type Reference type

Ni dung (tt)

Chuyn i kiu Boxing and unboxing Tham s ref, out, param Lnh lp for, while, do while, foreach Lnh phan nhanh switch, lnh nhy Cac kiu d liu phc:
Enumeration Struct Array
3

Visual studio 2008 environment


La mt mi trng lp trinh nhiu cng cu (tool-rich programming environment) cha moi tinh nng cn thit tao cac d an C# t nho n ln

Basic C# syntax
C# code is made up of a series of statements, each of which is terminated with a semicolon. C# is a block-structured language {} C# code is that it is case sensitive.

Console Application
Console Application: la ng dung ma input va output u nm trong console window. Console window: con goi la ca s du nhc lnh (MS-DOS command prompt)

ng dung console C# u tin


// Chng trnh C# u tin using System; using System.Collections.Generic; using System.Text; namespace HelloWorld { class Program { static void Main(string[] args) { Console.Write("Hello World!"); Console.ReadLine(); } } }
7

Cu trc chng trinh C#


Phn ch thch (option)
// Chng trnh C# u tin

Phn khai bao dng namespace (option)


using System; using System.Collections.Generic; using System.Text;

Phn nh ngha namespace va lp


namespace HelloWorld { class Program { static void Main(string[] args){ Console.Write("Hello World!"); Console.ReadLine(); } } }
8

Cau lnh (Statement)


Cac cau lnh c vit trong than ca phng thc (method) Thc hin mt cng vic nao Kt thc bi du chm phy (;)
Phng thc Main Cc cu lnh
namespace HelloWorld { class Program { static void Main(string[] args) { Console.Write("Hello World!"); Console.ReadLine(); } } }

Khong trng
Bao gm
K t trng, k t xung dong, k t tab Dong trng

S dung hp l chng trinh d oc


namespace HelloWorld {class Program { static void Main(string[] args) { Console.Write("Hello World!"); Console.ReadLine();} } } namespace HelloWorld { class Program { static void Main(string[] args) { Console.Write("Hello World!"); Console.ReadLine(); } } }

10

Ch thch
Ch thch (comment) c dng gii thch v chng trinh va cac cau lnh Gip cho chng trinh d hiu hn c bo qua khi bin dch Khng nh hng ti kt qu thc thi ca chng trinh C th phat sinh ra documentation ca chng trnh qua ch thch XML
11

Hai cach tao ch thch c bn


G phn ch thch sau cp k t // G phn ch thch gia cp k t /* v */
/* Chng trnh C# u tin In ra cu cho "Hello World" */ using System; namespace HelloWorld { class Program { static void Main(string[] args) { Console.Write("Hello World!"); // Xut ra cu cho Console.ReadLine(); // Ch nhn Enter } } }

12

XML Comment
Cho php phat sinh ra su liu dang XML Thch hp cho vic vit su liu ca d an ln Ch thch XML bt u vi triple slash (///) va cac tag ca XML Ch thch XML dng cho
User defined types Class, delegate, enum and struct Member of user defined types
13

V du: ng dung CONSOLE n gin

14

Using Namespace
gii quyt vn xung t tn (namecrashing) nn tao 1 container c t tn namespace
Hai class c th trng tn nhau nhng khng bi s dung nhm ln nu thuc 2 namespace khac nhau
Tn y u TextHello.Greeting

15

Using Namespace
Cac class trong .NET framework cung c sp xp vao cac namespace khac nhau. V du: lp Console thuc namespace System tham chiu n 1 lp nao , c th dng tn y :
Namespace.ClassName

Hoc tranh phi vit y tham chiu n namespace, c th dng using directive u chng trinh
16

Using Namespace

Bn namespace thng dung hay c dng trong cac chng trinh se c Visual Studio t ng a vao u mi chng trinh mi.

17

File program.cs
Mt chng trinh n gin nht bao gm: 1 file program.cs, trong file c 1 namespace mc nh va 1 class. Class: phi c ti thiu 1 hm Main static void Main(string[] args) { }
18

19

Tnh nng IntelliSense ca IDE


T ng hin th danh sach cac thanh phn ca class khi lnh c g vao ca s soan tho. C# se hin th thanh phn (member) ph hp vi cac k t ang c g vao, sau hin th tool tip cha m t tinh nng ca thanh phn.

20

Console I/O
oc k t vn bn t ca s console
Console.Read() gia tr tr v la int

Console.ReadLine() gia tr tr v la string

xut chui k t dng


Console.Write() / Console.WriteLine()
21

Printing on the Console


nh dang vn bn xut ra: Console.WriteLine( "{0}\n{1}", "Welcome to", "C# Programming!" );
i s 0

i s 1

i s cha chui inh dang


22

23

K t nh dang chui

24

25

Console I/O
Console.WriteLine()

\n: k t xung dng


26

Console I/O
/ F5

c chui
Xut chui Ch c 1 dng, mc ch l dng mn hnh
27

C# Is a strongly Typed Language


C# l mt ngn ng c kim sot cht che v mt kiu d liu Mi bin (variable) va i tng (object instance) trong h thng phi c xac nh kiu tng minh (well-defined type) Cho php compiler d dang kim tra c tinh hp l cac php toan trn cac bin va i tng.
28

Khai bao bin


Khai bao bin theo 2 dang:
<type><varName>; <type><varName>=<value>; Hay dng kt hp c 2 dang

V du:
int xSize, ySize; int age = 25; int xSize, ySize = 5;
29

Variable name
Hai quy tc:
K t u phi la ch cai (letter) hoc du _ hoc @. Cac k t tip theo c th la ch cai, _ hay s.

Phan bit CH HOA va ch thng Phi khac vi t kha (dng @ khc phuc)

30

Gan gia tr bin


Assign operator: = Ex
myInteger = 17; myString = "\"myInteger\" is";

31

Pham vi bin
Pham vi (scope)
c xac nh bi cp du { v } C th cha pham vi nho hn

V tr khai bao bin


Trong than phng thc: bin cuc b Trong than lp(trong class): thuc tnh

Bin trong C# ch c tac dung trong pham vi ma n c khai bao


32

Keyword
Cc t kha trong C# 2005
abstract as base bool break byte case catch char checked class const continue decimal default delegate do double else enum event explicit extern false finally fixed float for foreach get goto if implicit in operator int out interface override internal params is partial lock private long protected namespace public new readonly null ref object return sbyte sealed set short sizeof stackalloc static string struct switch this throw true try typeof uint ulong unchecked unsafe ushort using value virtual void volatile where while yield

33

Data types
There are two kinds of data types in C#.
Value Types (implicit data types, structs and enumeration) Reference Types (objects, delegates)

34

Values types
Bin loai tham tr (value types) cha 1 gia tr cu th ca loai d liu nao . V du: bin s nguyn (int) cha gia tr 7

35

Reference types
Bin loai tham chiu cha a ch b nh cha d liu ma bin tham chiu n.

36

Reference type
String s1= "Hello"; string s2 = "Bye"; string s3; s3 = s1;

s1

"Hello"

s3

s2

"Bye"

37

38

Implicit data types


Mi kiu d liu ngm nh u c anh xa thanh mt kiu tng ng trong Common Type System (CTS) va CLS (Common Language Specification).

39

Cac kiu d liu ngm nh trong C#

40

Cac kiu d liu ngm nh trong C#

41

B nh may tinh c t chc nh th nao? H iu hanh chia b nh thanh 2 chunk khac nhau, mi chunk c qun l theo 1 cach khac nhau.
Stack Heap

42

Value types va reference types


Tt c loai tham tr (value) u c tao trn stack. Tt c loai tham bin (reference) u c tao trn heap
Nhng con tro tham chiu (reference pointer) thi nm trn stack.

43

44

45

Stack
A stack is a data structure that store items in a first in first out (FIFO) fashion. It is an area of memory supported by the processor and its size is determined at the compile time.

46

Heap
A heap consists of memory available to the program at run time. Reference types are allocated using memory available from the heap dynamically (during the execution of program). The garbage collector searches for non-referenced data in heap during the execution of program and returns that space to Operating System.

47

Value type vs. Reference type

Characteristic Value type Variable hold Value Allocated Default Parameter Stack Zero Copy value

Reference type Reference Heap Null Copy reference

48

Constant
Mt hng la mt bin nhng tr khng thay i const int a = 100; // gia tr ko th thay i Hng bt buc phi c gan gia tr lc khai bo Tr ca hng c th c tnh toan vao lc bin dch Hng bao gi cung static
49

Constant
u im Chng trinh d oc, khc phuc nhng con s magic number trong code. Chng trinh d sa hn. Tranh li d dang hn, trinh bin dch se bao li nu gan lai gia tr cho hng

50

Constant
Minh hoa s dung hng
nh ngha hng

51

readonly
const: phi c gn gi tr khi khai bo

readonly: ko cn khi to trc, khi gn gi tr th sau ko thay i c

Cha c khi gn

Ko c thay i

52

Implicitly Typed Local Variables


In C#, every variable declared in the code must have an explicit type associated with it. But sometimes, when writing code for strongly typed languages, the amount of typing needed to declare such variables can be tedious

53

Bin loai suy din Type inference


var la t kha mi trong C# 3.0 Cach khai bao: var <varName>=<value>; Bin <varName> c loai ngm nh la loai ca value. V du: var myVar = 5; myVar la bin loai int
54

using System; using System.Collections.Generic; public class EntryPoint { static void Main() { var myList = new List<int>(); myList.Add( 1 ); myList.Add( 2 ); myList.Add( 3 ); foreach( var i in myList ) { Console.WriteLine( i ); } } }

An implicitly typed variable declaration must include an initialzer var newValue; // emits error CS0818

var a = 2, b = 1; var x, y = 4; Not permited

55

Chuyn i kiu d liu Type Conversion (cast)


Nhiu lc cn chuyn i d liu cho cac instances sang 1 loai d liu khac C 2 dang chuyn i
Implicit cast Explicit cast

56

Implicit cast
Tun theo promotion rules.
ch c php chuyn kiu nao ma khng lam mt d liu thi mi c php

Do C# t thc hin Khng cn lp trinh vin can thip

57

Implicit type cast


Xy ra khi
p t kiu nho qua kiu ln
int i = 59; double x = i;

p t lp dn xut qua lp c s
string s = "Hello"; object o = s;

58

Implicit type-cast
From sbyte byte short ushort int uint long, ulong float To short, int, long, float, double, decimal short, ushort, int, uint, long, ulong, float, double, decimal int, long, float, double, decimal int, uint, long, ulong, float, double, decimal long, float, double, decimal long, ulong, float, double, decimal float, double, decimal double

char

ushort, int, uint, long, ulong, float, double, decimal

59

Explicit type-cast
Do lp trinh vin ch nh Xy ra khi
p t kiu ln qua kiu nho: c th mt gia tr
double x = 74.86; int i = (int))x; // i = 74

p t lp c s qua lp dn xut
string s = "Hello"; object o = s; string s2 = (string)o;
60

Using Convert class


Thng dng khi cn chuyn i gia cac kiu khng c lin h vi nhau Convert.toDataType(SourceValue) V du: chuyn t chui sang s thc
string s1 = "56.8"; string s2 = "95"; double x = Convert.ToDouble(s1); // x = 56.8 int i = Convert.ToInt32(s2); // i = 95 byte j = Convert.ToByte(x); // j = 56, t dng

61

System.Object class

62

Boxing and unboxing


Dng ch vic chuyn d liu t stack sang heap va ngc lai Muc ch: ci thin vic thc thi chng trinh

63

Boxing
int i =42; Object o = i; I is a value type, so it exists in the stack. O is a reference type, so it must refer to objects on the heap. The runtime allocates a piece of memory from the heap, copies the value of integer i to this piece, and refers the object o to this copy.
64

Boxing
The automatic copying of an item from the stack to the heap is called boxing.

65

Boxing
If you modify the original value of a variable, the value on the heap will not change and vice versa.

66

Unboxing
Int i=o compile time error. The object o can refer to absolutely anything and not just an int. To obtain the value of the boxed copy, you must use a cast operation

67

Unboxing
Int I = 42; Object o = I; //boxes I = (int)o; // compiles okay

68

unboxing
Circle c = new Circle(42); Object o = c; // doesnt box because c is a reference variable; Int I = (int) o; //compiles okay but throws an exception at run time

69

70

Anh hng ca boxing/unboxing n vic thc thi chng trinh

71

checked & unchecked


The checked and unchecked statements are used to control the overflow checking context for integral-type arithmetic operations and conversions

throws OverFlowException

72

ref: tng t nh truyn tham chiu trong C/C++ T khoa ref phi c dng lc goi ham Cac tham s truyn dang ref phi c khi tao gia tr trc
s dng ref cho tham s khi gi hm

ref, out, param

Khai bo ref trc kiu d liu

73

ref, out, param


out: tng t nh ref Khac ref la ko cn khi tao gia tr trc khi truyn

Dng trc tham s khi gi hm Khai bo cho tham s

74

ref, out, param


Lun khai bao cui danh sch tham s

3 phn t

6 phn t

Mng array
75

Keyword this
public class list { private int size; ...
public SetSize (int size) { this.size = size; }

76

Loop
Tng t nh C: while, do while, for
while <iu kin> { // phn thn while do { // phn thn do while } while <iu kin>;

for( khi tao bin lp; <iu kin theo bin lp>; thay i bin lp) { // phn thn for }

Phi l gi tr bool: true, false

77

Loop
index = 10; while (index != 0){ Console.WriteLine(index); index--; }

Gi tr {true, false}

index = 0; do{ Console.WriteLine("Happens at least once"); }while (index < 0);

for(index = 0; index < 100; index++){ Console.Write(index); Console.Write("\t"); }

78

foreach
foreach( typedata identifier in objectArray) { // thn foreach }

Ch s dng bin i cho mi ln lp

S dng ch s mng nh bnh thng


79

switch

Biu thc switch gm: kiu s, k t, enum va chui S dung break, goto, return iu khin lung thc thi Nu ko nhan nao ph hp default Nu ko c default thc hin lnh sau switch
80

Jump
break
Thoat khoi vong lp

continue
Qua bc lp k

goto
Nhy n nhan S dung goto case <expression>, trong switch

81

return
Thoat khoi ham void
void Func1(int x) {

if (x == 0)
return; ... } int max(int a, int b) { if (a > b) return a; else return b; }
82

Tr v 1 gia tr ca ham

Demo Rolling a Six-Sided Die


Let us develop an application that simulates 20 rolls of a six-sided die and displays the value of each roll

83

Class Random (of namespace System)


Objects of class Random can produce random byte, int and double values. A new random-number generator object can be created as follows: Random randomNumbers = new Random(); The random-number generator object can then be used to generate random byte, int and double values
84

Class Random (of namespace System)


Method Next of class Random generates a random int randomValue = randomNumbers.Next(); Values returned by Next are actually pseudorandom numbersa sequence of values produced by a complex mathematical calculation.
85

Complex variable types


C# cung cp ba loai bin phc nhng rt thng dung:
Enumerations (often referred to as enums) structs (occasionally referred to as structures) Arrays

86

nh ngha Enumeration
Dng t kha enum nh ngha bin kiu enumerations
enum <typeName> { <value1>, <value2>, <value3>, ... <valueN> }
87

nh ngha Enumeration
Mt cach nh ngha khac: da vao kiu c s (underlying type) lu tr gia tr.
enum <typeName> :<underlyingType> { <value1>, <value2>, <value3>, ... <valueN> }

Underlying types of byte, sbyte, short, ushort, int, uint, long,and ulong.
88

nh ngha enumeration
Mc nh, mi gia tr c gan cho 1 gia tr tng ng vi underlying type value theo th t c nh ngha <value1> c gan gia tr 0, <value2> c gia tr 1 C th override php gan nay bng toan t =

89

Khai bao va s dung kiu enumeration


Khai bao bin kiu enumeration: <typeName><varName>; Gan gia tr cho bin: <varName> = <typeName>.<value>;

90

91

Struct (hay structure)


La kiu d liu c hp thanh t nhiu phn d liu c kiu d liu khac nhau. Cho php ngi dng t nh ngha kiu d liu ca ring minh.

92

nh ngha kiu struct


struct <typeName> { <memberDeclarations> }

Mi <memberDeclaration> c dang nh sau: <accessibility><type><name>; V du: struct route { public orientation direction; public double distance; }
93

Array
is a collection of values of a similar data type C# arrays are a reference type. Each array in C# is an object and is inherited from the System.Array class. Arrays are declared as:
<data type> [] <identifier> = new <data type>[<size of array>]

Ex: int [] integers = new int[10]; Hoc: int [] integers; integers = new int[10];
94

95

Array
The size of an array is fixed and must be defined before using it. Can use variables to define the size of the array:
int size = 10; int [] integers = new int[size];

Array can be defined by using the values


int [] integers = {1, 2, 3, 4, 5};

96

Truy xut cac phn t mng Accessing the values stored in an array
S dung toan t ch muc (indexing operator) [int index] Gia tr ch muc trong C# bt u t 0. Truy xut cac phn t ca mng:
Dng vong lp for va toan t ch s Dng vong lp foreach

Note:vong lp foreach ch cho php read-only. Khng th thc hin:


foreach (string friendName in friendNames) { friendName = "Rupert the bear};
97

V du 1
static void Main() { // declaring and initializing an array of type integer int [] integers = {3, 7, 2, 14, 65}; for(int i=0; i<5; i++) { Console.WriteLine(integers[i]); } }
98

V du 2
static void Main() { // declaring and initializing an array of type integer int [] integers = {3, 7, 2, 14, 65}; foreach(int i in integers) { Console.WriteLine(i); } }
99

Array
Ly kch thc mng qua thuc tnh Length
int Size = myArray.Length;

Nu thanh phn ca mng la kiu nh trc,

c th dng ham Sort ca Array sp xp


Array.Sort(myArray);

Dng ham Reverse ca Array o th t cac phn t trong mng


Array.Reverse(myArray);
100

Array

Dng phng thc tnh Sort ca lp Array sort artists

Dng phng thc tnh Reverse ca lp Array o th t artists

101

Multidimensional Arrays
A multidimensional array is simply one that uses multiple indices to access its elements. Cach khai bao <baseType>[,,,] <name>; V du: tao mng 2 chiu 3 hang 4 ct double[,] hillHeight = new double[3,4]; double[,] hillHeight = { { 1, 2, 3, 4 }, { 2, 3, 4, 5 }, { 3, 4, 5, 6 } };
102

Multi-dimensional Array
Datatype[,] array-name
Khai bao mng int 2 dng 3 ct
int[,] myMatrix = new int[2,3];

C th khi gan
int[,] myMatrix = new int[,] {{1,2},{3,4},{5,6},{7,8}}; int[,] myMatrix = {{1,2},{3,4},{5,6},{7,8}}; string[,] beatleName = {{"Lennon","John"}, {"McCartney","Paul"}, {"Harrison","George"}, {"Starkey","Richard"}};

103

104

Multi-dimensional Array

Truy cp tun t theo kiu mng 1 chiu

Truy cp theo dng dng ct qua ch mc i v j


105

Jagged Array (Arraysof Arrays)


Datatype[ ][ ] array-name
Jagged la mng ma mi phn t la mt mng c kch thc khc nhau Nhng mng con nay phi c khai bao ring Khai bao mng 3 dong, mi dong la mt mng 1 chiu
int[][] a = new int[3][]; a[0] = new int[4]; a[1] = new int[3]; a[2] = new int[1];

Khai bo s dng, hng Khai bo s ct ring cho tng dng


106

107

Jagged Array

Truy cp theo dng, ct

Truy cp dng foreach

108

Jagged array
A jagged array cannot be completely created with a single array creation expression.
Ex: int[][] c = new int[ 2 ][ 5 ]; // error

Each one-dimensional array in the jagged array must be initialized separately.


Ex: int[][] c; c= new int[ 2 ][ ]; // create 2 rows c[ 0 ]= new int[ 5 ]; // create 5 columns for row 0 c[ 1 ]= new int[ 3 ]; // create 3 columns for row 1
109

Demo Cach tao mng chui


Lam quen 1 s phng thc thng dung ca lp string. Tao 1 mng ma mi phn t la 1 word trong 1 chuoi duoc nhap vao luc khoi tao lop private string[] myWords;

110

String class

111

You might also like