You are on page 1of 69

Introduction to C#

The Languague for .NET

Lecturer: NGUYEN Van Hieu


nvhieuqt@dut.udn.vn
Contents
u Overview u Structs
u Structure of C# u Classes
programs
u Unboxing/Boxing
u Types
u Operators
u Identifier
u Expressions
u Keywords
u Console I/O
u Variable
u Statements
u Constant
u Arrays
u Constant-readonly
u ref, out, param
u Enumerations

2
Overview
u Features of C#
u Very similar Java
v 70 Java, 10% C++, 5% Visual Basic, 15
% new
Overview
u New features in C#
Overview
u Hello World
Structure of C# Programs

u Nếu ko có namespace Þ namespace mặc định ko tên


u Namespace có thể chứa: struct, interface, delegate, enum
u Namespace có thể “reopened” ở một tệp khác
u Trường hợp đơn giản: 1 lớp, 1 file cs và namespace mặc định

6
Structure of C# Programs

using <namespace sử dụng>



namespace <Tên Namespace>
{
[Khóa truy xuất] class <Tên lớp>
{
public static void Main()
{

}
// thành viên khác …
}
// lớp khác …

7
Structure of C# Programs

u A program consisting of 2 Files

8
Types
u Type System

u Notes:
v Tất cả các kiểu trên đều tương thích với kiểu object
v Các phép toán trên kiểu object có thể gán cho chúng
Types
u Value types versus Reference types
Simple Types
Name CTS Type Bit Range
sbyte System.SByte 8 -128..127
short System.Int16 16 (-32768 .. 32767) Kiểu nguyên
int Sytem. Int32 32 -231..231-1
long Sytem. Int64 64 -263..263-1
byte System.SByte 8 0..255
ushort System.UInt16 16 (0 .. 65535) Kiểu thực
uint System.UInt32 32 0..232-1
ulong System.UInt64 64 0..264-1

float System.Single 32 xấp xỉ từ 3,4E - 38 đến 3,4E+38

double System.Double 64 1,7E-308 đến 1,7E+308


decimal System.Decimal 128 Có độ chính xác đến 28 con số
bool System.Boolean Kiểu true/false
char System.Char 16 Ký tự unicode
11
Simple Types
u Compatibility between Simple types
Value types
u Chứa giá trị trực tiếp
u Không thể null int i = 59;
double x = 7.83;
v Phải chứa giá trị xác định int a = i;

u Bao gồm
i 59
v Simple types
v Enum: enum State { Off, On } x 7.83
v Struct: struct Point{int x, y; }
a 59

13
Reference types
u object: Sytem.Object
v Kiểu dữ liệu gốc, cha của tất cả các kiểu
dữ liệu trong C#
v object o = new object();

u string: Sytem.String
v Chuỗi ký tự Unicode
v string s1 = “CNTT”;
v string s2 = “Hi “;
v string s = s1 + s2;

14
Reference types
u Chỉ tới nơi chứa dữ liệu
u Có thể null string s1 = "Hello";
string s2 = "Bye";
v null: không chỉ tới bất kỳ
string s3;
đâu s3 = s1;
u Bao gồm
v class
s1 "Hello"
v string, object
v interface s3
v array
v delegate
s2 "Bye"

15
Identifier
u Tên gọi được đặt ra để đại diện
v Định danh mang tính gợi nhớ
u Tạo định danh
v HelloWorld, Program, Perform,…
v à phải khai báo trước khi sử dụng
u Dùng định danh có sẵn
v Console, WriteLine, ReadLine,…
v à phải chỉ ra nơi chứa định danh
(namespace)

16
Identifier
u Bao gồm chữ cái, chữ số, ký tự gạch
dưới
u Không được bắt đầu bằng chữ số
u Không trùng với từ khóa
u Phân biệt CHỮ HOA và chữ thường
u Trong cùng phạm vi không được trùng
tên
Keywords
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 goto
if implicit in int interface internal
is lock long namespace new null
object operator out override params private
protected public readonly ref return sbyte
sealed short sizeof stackalloc static string
struct switch this throw true try
typeof uint ulong unchecked unsafe ushort
using virtual void volatile while
Variable
u Biến là nơi mang dữ liệu
u Dữ liệu của biến
v Nằm trong bộ nhớ vật lý (physical RAM)
v Có thể thay đổi giá trị
u Phải khai báo biến trước khi dùng

19
Variable

Cú pháp khai báo biến

[AccessModifier] Type Variable;


Public int

Private string
Protected float
Variable
Sử dụng từ khóa như tên của một biến,
thêm tiền tố ‘@’ trước từ khóa.

using System;
class VariableDemo
{
public static void Main()
{
string @string;
@string = ”string là từ khóa, nhưng được sử dụng như là
một biến”;
Console.WriteLine (@string);
}
}
Constant
u Một hằng là một biến, nhưng trị không đổi
u Cú pháp:
public const double PI = 3.1415926535897932;
const string COMPANY_NAME = “Asoft_Linh";

u Hằng bắt buộc phải được gán giá trị lúc khai
báo

22
Constant
u Ưu điểm
v Chương trình dễ đọc
v Chương trình dễ sửa hơn.
v Tránh lỗi dễ dàng hơn, trình biên dịch sẽ
báo lỗi nếu gán lại giá trị cho hằng

23
Constant
u Minh họa sử dụng hằng

24
Constant-readonly
u const: phải được gán giá trị khi khai báo
u readonly: ko cần khởi tạo trước, khi gán giá trị
thì sau đó ko thay đổi được

25
Enumerations
u List of named constants
u Declaration(directly in a namespace):

u Use:
Operations on Enumerations

u The compiler does not check if the result is a


valid enumeration value
u Class System.Enum provides operations on
enumerations (GetName, Format, GetValue)
Enumerations

28
Structs
u Declaration(directly in a namespace):

u Use:
Structs
struct Books {
private string title;
private string author;
private string subject;
private int book_id;
public void getValues(string t, string a, string s, int id){
title = t; author = a; subject = s; book_id = id;
}
public void display(){
Console.WriteLine("Title : {0}", title);
Console.WriteLine("Author : {0}", author);
Console.WriteLine("Subject : {0}", subject);
Console.WriteLine("Book_id :{0}", book_id);
}
};
Structs
public class testStructure {
public static void Main(string[] args) {
Books Book1 = new Books();
Books Book2 = new Books();

Book1.getValues("C# Programming",
“Hieu", "C# Programming Tutorial",6495407);

Book2.getValues("Telecom Billing",
"Zara Ali", "Telecom Billing Tutorial", 6495700);

Book1.display();
Book2.display();
Console.ReadKey();
}
}
Classes
u Declaration(directly in a namespace):

u Use:
Differences between Classes and Structs
Type cast
u Implicit type-cast
u Explicit type-cast
Boxing & Unboxing
u Boxing: value types(int, enum, struct)
àobject.
Using Convert class
u Thường dùng khi cần chuyển đổi
giữa các kiểu không có liên hệ với
nhau
Convert.toDataType(SourceValue)
u Ví dụ: chuyển từ chuỗi sang số
thực
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 dùng

36
Operators
u Độ ưu tiên toán tử giống C++ và Java
u Sô học: +, -, *, /, %, ++, --
u Lôgic: &&, ||, !, ^, true, false
u Trên bit: &, |, ^, ~, <<, >>
u So sánh: ==, !=, <, >, <=, >=
u Gán: =, +=, -=, *=, /=, %=, &=, |=, ^=, <<=,
>>=
u as, is, sizeof, typeof
u khác: ., [], (), ?:, new, checked,
unchecked, unsafe
Operators
sử dụng toán tử is

8 byte

38
Operators
Overflow is not checked by defult

throws OverFlowException

39
Expressions
u Cú pháp tượng tự C++ và Java
u Ví dụ:
a = b = c = 20;
(а+5)*(32-a)%b;
“I love" + “you”; // (string)
Math.Cos(Math.PI/x);
(int) arr[idx1][idx2]
new Student()
(currentValue <= MAX_VALUE)
Console I/O

Đọc chuỗi

Xuất chuỗi
Chờ đọc 1 dòng, mục đích là dừng màn hình

41
Console I/O
u Để đọc ký tự văn bản từ cửa sổ
console
v Console.Read() giá trị trả về là int

v Console.ReadLine() giá trị trả về là string

u Để xuất chuỗi ký tự dùng


v Console.Write() / Console.WriteLine()
Console I/O
u Console.WriteLine()

43
Statements
u Empty statement

u Assigment

u Method call
If statement
u Syntax
if (expression)
{
//expression – giá trị kiểu bool
}

u Example
If statement

string str = ”hello”;


if (str)
System.Console.WriteLine (“The value is True”);
if (str == “hello”)
System.Console.WriteLine (“The Value is True”);

Error CS0029 : Cannot implicitly convert type ‘string'


to 'bool'
Switch statement
q Syntax
switch(variable)
{
case value:
//Statements
break;
case value:
//Statements
break;
default:
//Statements
break;
}
§ Variable có thể kiểu số, ký tự, enum và chuỗi
§ Sử dụng break, goto, return để điều khiển luồng thực thi
Switch statement
q Example
Switch with gotos
q Example
Loops
u while

u do while Notes:
+ break
+ continue

u for
Loops
index = 10;
while (index != 0){
Console.WriteLine(index); {true, false}
index--;
}

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

for(index = 0; index < 100; index++){


Console.Write(index);
Console.Write("\t");
}
foreach statement
u For iterating over collections and arrays
u Syntax
foreach (Type Identifier in expression ){
// Statements
}
foreach statement
u Examples
Jumps
u break;
v For exiting a loop or switch statement
u continue;
v Continues with the next loop iteration
u goto case 3:
u goto mylabel;
v Nhảy đến nhãn
v Mylable:
return statement
u Returning from a void method

u Returning a value from a function method


Arrays
u One-dimensional Arrays
u Syntax
Datatype[ ] array-name

u Example
v int [ ] a = new int[5];
v int [ ] b = new int[]{3,4,5};
v int [ ] c = {3,4,5};
v SomeClass [ ] d = new SomeClass[10];
v SomeStruct[ ] e = new SomeStruct[10];
v int len = a.Length;
Arrays
u One-dimensional Arrays

Dùng phương thức tĩnh Sort Dùng phương thức tĩnh Reverse
của lớp Array để sort của lớp Array để đảo thứ tự
Multidimensional Arrays
Datatype [ , ] array-name
u Rectangular
v int [ , ] a = new int[2 , 3];

v int x = a[0,1]
v int len = a.Length; //6
v len = a.GetLength(0); //2
v len = a.GetLength(1);// 3

58
Multidimensional Arrays

Truy cập tuần tự theo kiểu Truy cập theo dạng dòng cột
mảng 1 chiều qua chỉ mục i và j
59
Jagged Arrays

Datatype [ ][ ] array-name
u Jagged (like in Java)
v int[][] a = new int[2][];
a[0] = new int[3];
a[1] = new int[4];
v Int x = a[0][1];
v Int Len = a.Length; //2
v Len = a[0].Length; // 3
Jagged Arrays

Truy cập theo dòng, cột Truy cập dùng foreach

61
ref, out, param
u ref: tương tự như truyền tham chiếu trong
C/C++
u Từ khoá ref phải được dùng lúc gọi hàm
u Các tham số truyền dạng ref phải được khởi
tạo giá trị trước
sử dụng ref cho
tham số khi gọi hàm

Khai báo ref trước


kiểu dữ liệu

62
ref, out, param
u out: tương tự như ref
u Khác ref là ko cần khởi tạo giá trị trước
khi truyền

Dùng trước tham


số khi gọi hàm

Khai báo cho tham số

63
ref, out, param

Luôn khai
báo ở cuối
danh sách
tham số

3 phần tử 6 phần tử Mảng array

u CHo phép truyền một số biến vào hàm mà ko cần phải tạo mảng
64
This
public class list
{
private int size;

...

public SetSize (int size)


{
this.size = size;
}

65
Summary
u Cú pháp khá giống với Java và
C/C++

66
Thank You

67
67
Tài liệu tham khảo
u MSDN Training, Programming C# (MOC 2124C),
Module 2: Overview of C#
u MSDN Training, Programming C# (MOC 2124C),
Module 3: Using Value-Type Variables
u Jessy Liberty, Programming C#, Second Edition,
O’Reilly, 2002, ISBN 0-596-00309-9
u Svetlin Nakov, .NET Framework Overview –
http://www.nakov.com/publications/Nakov-DotNET-
Framework-Overview-english.ppt
u MSDN, C# Keywords –
http://msdn.microsoft.com/library/en-
us/csref/html/vclrfcsharpkeywords_pg.asp
u MSDN, C# Built-in Types Table –
http://msdn.microsoft.com/library/en-
us/csref/html/vclrfbuiltintypes.asp
Tài liệu tham khảo
u MSDN, Common Type System Overview –
http://msdn.microsoft.com/library/en-
us/cpguide/html/cpconcommontypesystemoverview.asp
u MSDN, Enumerations –
http://msdn.microsoft.com/library/en-
us/cpguide/html/cpconEnumerations.asp
u MSDN, C# Operators –
http://msdn.microsoft.com/library/en-
us/csref/html/vclrfCSharpOperators.asp
u MSDN, Statements (C# Programmer's Reference) –
http://msdn.microsoft.com/library/en-
us/csref/html/vclrfstatements.asp
u MSDN, XML Documentation Tutorial (C#
Programmer's Reference) –
http://msdn.microsoft.com/library/en-
us/csref/html/vcwlkxmldocumentationtutorial.asp

You might also like