Anda di halaman 1dari 65

Chapter 2.

Core C# Programming Constructs


Hoang Anh Viet
VietHA@it-hut.edu.vn

HaNoi University of Technology


1

Objectives
This chapter surveys the C# language syntax. I introduce you to the two fundamental kinds of types within the CLR: value types and reference types. This chapter also describes namespaces and how you can use them to logically partition types and functionality within your applications.

Microsoft

Roadmap
2.1. C# Is a strongly Typed Language 2.2. Expression 2.3. Statements and Expressions 2.4. Types and Variabless 2.5. NameSpaces 2.6. Control Flows

Microsoft

2.1. C# Is a strongly Typed Language

Every variable and object instance in the system is of a well-defined type This enables the compiler to check that the operations to perform on variables and object instance are valid It is always best to find bugs at compile time rather than run time Example: Method ComputeAvg(): computes the average of two integers
and returns the result

Microsoft

ComputeAvg accepts two integers and returns a double. If passing an instance of Apple type, the compiler will complain and stop

double ComputeAvg( int param1, int param2 ) { return (param1 + param2) / 2.0; }

object ComputeAvg( object param1, object param2 ) { return ((int) param1 + (int) param2) / 2.0; }
Convert objects into integers Passing an instance of Apple type causes an exception( the instance cant be convert into integer
object keyword: an alias of System.Object class Object is not a numeric type

Microsoft

Roadmap

2.1. C# Is a strongly Typed Language 2.2. Expression 2.3. Statements and Expressions 2.4. Types and Variabless 2.5. NameSpaces 2.6. Control Flows

Microsoft

2.2. Expressions

Expressions in C# are identical to expressions in C++ and Java. Are built using operands, eg. variables or types within an application, and operators Operators can be overloaded Operators can have different meaning in different contexts
C# operator precedence:

Eg: the + operator can mean string concatenation using with string operands Example : OverandOver.csc When an expression contains multiple operators, the precedence of the
operators controls the order in which the individual operators are evaluated Entries at the top of the table have higher precedence Operators within the same category have equal precedence.

Microsoft

Category Primary

Expression x.m x(...) x[...] x++ x-new T(...) new T(...){...} new {...} new T[...] typeof(T) checked(x) unchecked(x) default(T) delegate {...}

Description
Member access Method and delegate invocation Array and indexer access Post-increment Post-decrement Object and delegate creation Object creation with initializer Anonymous object initializer Array creation Obtain System.Type object for T Evaluate expression in checked context Evaluate expression in unchecked context Obtain default value of type T Anonymous function (anonymous method)

Microsoft

Category Unary

Multiplicative

Additive

Shift

Expression +x -x !x ~x ++x --x (T)x x * y x / y x % y x + y x y x << y x >> y

Description
Identity Negation Logical negation Bitwise negation Pre-increment Pre-decrement Explicitly convert x to type T Multiplication Division Remainder Addition, string concatenation, delegate combination Subtraction, delegate removal Shift left Shift right

Microsoft

Category Relational and type testing

Equality Logical AND Logical XOR Logical OR

Expression x < y x > y x <= y x >= y x is T x as T x == y x != y x & y x ^ y x | y

Description Less than Greater than Less than or equal Greater than or equal Return true if x is a T, false otherwise Return x typed as T, or null if x is not a T Equal Not equal Integer bitwise AND, boolean logical AND Integer bitwise XOR, boolean logical XOR Integer bitwise OR, boolean logical OR

Microsoft

10

Roadmap

2.1. C# Is a strongly Typed Language 2.2. Expression 2.3. Statements and Expressions 2.4. Types and Variabless 2.5. NameSpaces 2.6. Control Flows

Microsoft

11

2.3 Statements and Expressions


The actions of a program are expressed using statements Several different kinds of statements:

A block: consists of a list of statements written between the delimiters { and }


{x=69;y=96}

Declaration statements: are used to declare local variables and constants


int a; int b = 2, c = 3;

Microsoft

12

Statements and Expressions(2)

Epression statements are used to evaluate expressions


Console.WriteLine(Goodbye);

Selection statements are used to select one of a number of possible statements for execution based on the value of some expression if, switch
if(continue == true) {x=69;} else {x=96;}

Iteration statements are used to repeatedly execute an embedded statement while, do, for, foreach
while (i ++< Length) { Console.WriteLine(args[i]); }

Microsoft

13

Statements and Expressions(3)

Jump statements are used to transfer control - break, continue, goto, throw, return, and yield
1. while (true) { 2. int n = Console.Read(); 3. if (n == 69) break; 4. Console.WriteLine(n); 5. }

The try...catch statement is used to catch exceptions that occur during execution of a block, and the try...finally statement is used to specify finalization code that is always executed, whether an exception occurred or not

Microsoft

14

Statements and Expressions(4)

The checked and unchecked statements are used to control the overflow checking context for integral-type arithmetic operations and conversions. Ex : Exam.csc The lock statement is used to obtain the mutual-exclusion lock for a given object, execute a statement, and then release the lock The using statement is used to obtain a resource, execute a statement, and then dispose of that resource

Microsoft

15

Roadmap

2.1. C# Is a strongly Typed Language 2.2. Expression 2.3. Statements and Expressions 2.4. Types and Variabless 2.5. NameSpaces 2.6. Control Flows

Microsoft

16

Value Types and Reference Types

Value types:

Living places: On the stack On the heap: only if they are members of reference types or if they
are boxed

Reference types:

Are copied by value by default when passed as parameters to methods or assigned to other variables
Living place: on the heap Variables used to manipulate them are references to objects on the managed heap

Microsoft

17

Value Types

Contain directly their value and are customarily created statically Initialization: using the new statement Derive from System.ValueType Primitives: int, float, char and bool Others: enum, struct

Microsoft

18

Reference Types

The lifetime of the resulting object is controlled be garbage collection services provided by CLR The reference holds the location of an object created on the managed heap Derive from System.Object and created with the new keyword Types: interfaces, arrays and delegates

Microsoft

19

Example:

Value Type i s Reference Type

int i = 123; string s = "Hello world"; 123 "Hello world"

Microsoft

20

Value Types contain Reference Types

Example:

Reference type

class ShapeInfo { public string infoString; public ShapeInfo(string info) { infoString = info; } }

Microsoft

21

Value type
struct Rectangle {

The Rectangle structure contains a reference type member

public ShapeInfo rectInfo; public int rectTop, rectLeft, rectBottom, rectRight; public Rectangle(string info, int top, int left, int bottom, int right) { rectInfo = new ShapeInfo(info); rectTop = top; rectBottom = bottom; rectLeft = left; rectRight = right; } public void Display() { Console.WriteLine("String = {0}, Top = {1}, Bottom = {2}," + "Left = {3}, Right = {4}", rectInfo.infoString, rectTop, rectBottom, rectLeft, rectRight); } }

Microsoft

22

static void ValueTypeContainingRefType() { Console.WriteLine("-> Creating r1"); Rectangle r1 = new Rectangle("First Rect", 10, 10, 50, 50); . Console.WriteLine("-> Assigning r2 to r1"); Rectangle r2 = r1; Console.WriteLine("-> Changing values of r2"); r2.rectInfo.infoString = "This is new info!"; r2.rectBottom = 4444; .

Create the first Rectangle.

Assign a new Rectangle to r1

Change some values of r2. Print values of both rectangles


23

r1.Display(); r2.Display();
}

Microsoft

Result:

Microsoft

24

Default Variable Initialization

The following categories of variables are automatically initialized to their default values:

Static variables. Instance variables of class instances. Array elements.

For a variable of a reference-type, the default value is null For a variable of a value-type, the default value is the same as the value computed by the value-types default constructor
25

Microsoft

Default Variable Initialization(2)

Value-types default constructor:


All value types implicitly declare a public parameterless instance constructor called the default constructor Default constructor returns the default value for the value type:
Value Type
sbyte, byte, short, ushort, int, uint, long, and ulong char

Default Value
0

'\x0000'

Microsoft

26

Default Variable Initialization(3)


Value Type float double decimal bool enum-type E Default Value 0.0f 0.0d 0.0m false 0, converted to the type E

struct-type

All value type fields: default value of Value Type


All reference type fields: null

Microsoft

27

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

Microsoft

28

Implicitly Typed Local Variables(2)

var is a new keyword in C# 3.0 Declaring a local variabl using the new var keyword asks the compiler to reserve a local memory slot and attach an inferred type to that slot At compilation time, compiler can initialize variables without asking the type explicitly How to use: var localVariant = <expression>
localVariant is init with type of <expression>

Microsoft

29

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
Microsoft
30

Implicitly Typed Local Variables(3)

Restriction:

var cannot use with multiple variable declarators


var x=69, y=9.6; //Error, Implicitly-typed local variables cannot have multiple declarators

Declarator implicitly typed local variables must include a localvariable-initializer


var x; //Error, no initializer to infer type from

The local-variable-initializer must be an expression The initializer expression must have a compile-time type
var u = x => x + 1; //Error, anonymous functions do not have a type

The initializer expression cannot refer to the declared variable itself


31

Microsoft

Type Conversion

Many times, its necessary to convert intstances of one type to another int defaultValue = 12345678; Implicit Conversion: long value = defaultValue;
int smallerValue = (int) value;
public class EntryPoint { static void Main() { int employeeID = 303; object boxedID = employeeID; employeeID = 404; int unboxedID = (int) boxedID; System.Console.WriteLine( employeeID.ToString() ); System.Console.WriteLine( unboxedID.ToString() ); } } 32

Explicit Conversion:

Microsoft

Implicit Conversions

One type of data is automatically converted into another type of data No data loss Implicit Numerical Conversion
1. long x; 2. int y = 25; 3. x = y; //implicit numerical conversion

Implicit Enumeration Conversion

Permit the decimal, integer, literal to be converted to any enum type

Microsoft

33

Implicit Conversions(2)

Implicit Reference Conversion


Microsoft

From any reference type to object. From any class type D to any class type B, provided D is inherited from B. From any class type A to interface type I, provided A implements I. From any interface type I2 to any other interface type I1, provided I2 inherits I1. From any array type to System.Array. From any array type A with element type a to an array type B with element type b provided A & B differ only in element type (but the same number of elements) and both a and b are reference types and an implicit reference conversion exists between a & b. From any delegate type to System.Delegate type. From any array type or delegate type to System.ICloneable. From null type to any reference type.
34

Implicit Conversions(3)

Boxing Conversions

Conversion of any value type to object type


1. int x = 10; 2. object o = x; //Boxing

Microsoft

35

Explicit Conversions

Using the casting operator () May be loss data Explicit Numerical Conversions
1. int x = (int) 26.45; //Explicit conversion 2. Console.WriteLine(x); // Displays only 26

Explicit Enumeration Conversions


From sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double or decimal to any enum type. From any enum type to sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double or decimal. From any enum type to any other enum type
36

Microsoft

Explicit Conversions(2)

Explicit Reference Conversions


Microsoft

From object to any reference type. From any class type B to any class type D, provided B is the base class of D From any class type A to any interface type I, provided S is not sealed and do not implement I. From any interface type I to any class type A, provided A is not sealed and implement I. From any interface type I2 to any interface type I1, provided I2 is not derived from I1. From System.Array to any array type. From System.Delegate type to any delegate type. From System.ICloneable to any array or delegate type.

37

as and is Operators

The as operator

is used to perform conversions between compatible reference types The as operator is like a cast operation. However, if the conversion is not possible, as returns null instead of raising an exception Checks if an object is compatible with a given type An is expression evaluates to true if the provided expression is non-null, and the provided object can be cast to the provided type without causing an exception to be thrown The is operator only considers reference conversions, boxing conversions, and unboxing conversions
38

The is operator

Microsoft

Generics

Support for generics is one of the most exciting new additions to the C# language Using the generic can define a type that depends upon another type that is not specified at the point of definition Example:

A collection may be a list, queue or stack

Microsoft

39

Generics
1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19.
Microsoft

public class List List<ItemType> { private object[] elements; ItemType[] elements; private int count;

public void Add(object element) { { Add(ItemType element) if (count == elements.Length) Resize(count*2); elements[count++] = element; }
public object this[int index] { { ItemType this[int index] get { return elements[index]; } set { elements[index] = value; } }List<int> List intList intList = new=List(); new List<int>(); public int Count { intList.Add(1); get { return count; } intList.Add(2); }intList.Add("Three"); int i = intList[0]; (int)intList[0]; // Argument No boxingis boxed // No Argument boxingis boxed // Compile-time Should be an error // No Cast cast required required
40

1. 2. 3. 4. 5. 6. } 7.

Generics(2)

Why generics?

Type checking, no boxing, no downcasts Reduced code bloat (typed collections)

How are C# generics implemented?


Instantiated at run-time, not compile-time Checked at declaration, not instantiation Work for both reference and value types Complete run-time type information

Microsoft

41

Generics(3)

Can be used with various types

Class, struct, interface and delegate

Can be used with methods, parameters and return types Support the concept of constraints

One base class, multiple interfaces, new()

Microsoft

42

Generics(4)

Type parameters can be applied to

Class, struct, interface, and delegate types

class Dictionary<KeyType, ValueType> {...}

struct Pair<FirstType, SecondType> {...}


interface IComparer<T> {...} Dictionary<string, Customer> customerLookupTable; delegate ResType Func<ArgType, ResType>(ArgType arg); Dictionary<string, List<Order>> orderLookupTable; Dictionary<int, string> numberSpellings;
Microsoft
43

Generics(5)

Type parameters can be applied to


Class, struct, interface, and delegate types Methods

1. class Array 2. { 3. public static T[] Create<T>(int size) { 4. return new T[size]; 5. } 6. string[] namesvoid = Array.Create<string>(3); 7. 1. public static Sort<T>(T[] array) { names[0] = "Jones"; 8. 2. ... names[1] = "Anderson"; 9. 3. } 10. 4. } names[2] = "Williams"; 5. Array.Sort(names);
Microsoft

44

Generics(6)

Constraints

One base class, multiple interfaces, new() Specified using where clause

1. interface interface IComparable<T> IComparable{int {int CompareTo(object CompareTo(T obj);} obj);} 2. class Dictionary<K, V> where K: IComparable 3. class class { Dictionary<K, V> Dictionary<K, V>: IDictionary<K, V> where 4. public void Add(K key, V value) { 4. { K: IComparable<K>, 5. public ... void Add(K key, V value) { 5. V: IKeyProvider<K>, 6. ... switch (key.CompareTo(x)) { 6. V: IPersistable, 7. switch ... (((IComparable)key).CompareTo(x)) { 7. V: new() 8. } ... 8. { 9. } } 9. ... 10. } } 10. } 11. }

Microsoft

45

Roadmap

2.1. C# Is a strongly Typed Language 2.2. Expression 2.3. Statements and Expressions 2.4. Types and Variabless 2.5. NameSpaces 2.6. Control Flows

Microsoft

46

2.5 Namespaces

Need for Namespaces Using namespace directives Using alias directives Standard Namespaces in .NET

Microsoft

47

Need for Namespaces


Namespaces allow you to create a system to organize your code A good way to organize your namespaces is via a hierarchical system Placing code in different sub-namespaces can keep your code organized using keyword used to work with namespaces:

Create an alias for a namespace (a using alias). Permit the use of types in a namespace, such that, you do not have to qualify the use of a type in that namespace (a using directive).
48

Microsoft

Using namespace directives


1. 2. 3. 4. 5. 6. 7. 8. 9.
Microsoft

using System; Console is a class of class Hello namespace System. { static void Main() { string hello = Hello!; Console.WriteLine(hello); } If not use using System; you must use method }
System.Console.WriteLine() to write hello
49

Using alias directives

using identifier = namespace-or-type-name ; For example:


1. 2. 3. 4. 5. 6. 7. 8. 9. namespace N1.N2 { class A {} } namespace N3 { using A = N1.N2.A; class B: A {} }

Microsoft

50

Standard Namespaces in .NET


Fundamentals System System.AddIn System.IO System.Linq

System.Collections
System.ComponentModel System.Configuration System.Diagnostics System.DirectoryServices System.EnterpriseServices System.Globalization System.IdentityModel.Claims
Microsoft

System.Reflection
System.Resources System.Runtime System.Security System.ServiceProcess System.Text System.Threading System.Transactions
51

Standard Namespaces in .NET(2)

Windows Presentation Foundation System.Windows Windows Forms System.Drawing System.Media System.Windows.Forms ASP.NET System.Web

Microsoft

52

Standard Namespaces in .NET(3)

Communications and Workflow System.Messaging System.Net System.Net.Sockets System.ServiceModel System.Web.Services System.Workflow DATA, XML and LINQ System.Data System.Xml

Microsoft

53

Roadmap

2.1. C# Is a strongly Typed Language 2.2. Expression 2.3. Statements and Expressions 2.4. Types and Variabless 2.5. NameSpaces 2.6. Control Flows

Microsoft

54

2.6 Control Flow


if-else, switch while, do-while, and for foreach break, continue, goto, return, and throw

Microsoft

55

if-else construct
1. (condition) if (salary > 2000) if 2. Console.Write("Salary is greater than 2k"); statement(s)_1 //The original result [else //The alternative result 1. statement(s)_2] if (salary > 2000)

2. Console.Write("Salary is greater than 2k"); // The original result condition is a relational or logical expression. 3. else 4. Console.Write("Salary is less than or equal statement(s)_1 is a statement (or a block of statements) that is to 2k"); // The alternative result

executed if the condition is true. statement(s)_2 is a statement (or a block of statements) that is executed if the condition is false

Microsoft

56

Nested if-else Statements


if (condition_1) statement_1; else if (condition_2) statement_2; else if (condition_3) statement_3; ... else statement_n;
Microsoft
57

switch Construct

expression represents a value that corresponds to the associated switch choice

1. using System; switch (expression) 2. class Switch statement(s) is a { 3. { statement or 4. void main() case static constant-1: statement(s); block of statements that is 5. { jump-statement executed if the 6. int n = 2; case constant-2: statement(s); corresponding 7. switch (n) condition is jump-statement 8. { evaluated true 9. case 1: Console.WriteLine("n=1"); case constant-3: 10. break; ... jump-statement is 11. default: Console.WriteLine("n=2"); a branching [default: statement(s); 12. break; statement to jump-statement] 13. } transfer control 14. } default deals } outside the specific with 15. } all the case, such as other cases break or goto (explained later) Microsoft
58

while Loop
1. using System; while (control_expression) 2. class WhileLoop 3. statement(s); { 4. static void Main() control_expression is a condition be satisfied during 5. { the loop execution. 6. int counter=0; while(counter++ <= block 10) of statements) 7. statement(s) is a statement (or the 8. { to be executed. 9. Console.WriteLine(counter); 10. } 11. } 12. }

Microsoft

59

do-while Loop
1. do using System; 2. class DoWhileLoop statement(s) 3. { 4. void Main() while static (control_expression); 5. { 6. control_expression is a condition to be satisfied during int counter=0; 7. do the loop execution. 8. { statement(s) is a statement (or the block of statements) 9. Console.WriteLine(counter); to be executed. 10. } 11. while(counter++ <= 10); 12. } 13. }

Microsoft
60

for Loop
1. using System; for ([initialization]; 2. class ForLoop [control_expression]; counter_update]) 3. { statement(s) 4. static void Main() 5. { initialization is the counter initialization statement. 6. for (int counter = 1;counter<=10; control_expression is a condition to be satisfied during counter=counter +2) 7. { the loop execution. 8. Console.WriteLine(counter); counter_update is the counter increment or decrement 9. } statement. 10. } } 11. statement(s) is the statement or block of statements to

be repeated.
Microsoft
61

The foreach Loop


1. using System; foreach (type identifier in expression) 2. class ForeachLoop statement(s); 3. { static void such Main() 4. type is the data type, as int or string. 5. { 6. identifier is int[,] the variable name. myIntArray = {{1, 3, 5}, 4, 6} }; 7. expression is the name of the array (or{2, collection). 8. foreach(int i in myIntArray) statement(s) is the statement or block of statements to 9. Console.Write("{0} ", i); be executed. 10. } 11. }

Microsoft

62

Branching Statements

break

terminates the closest enclosing loop or switch statement in which it appears

goto:

goto label;

is not recommended because it corrupts the program structure

goto case expression; goto default; (in case struct)

continue

passes control to the next iteration of the enclosing iteration statement in which it appears

Microsoft

63

Branching Statements(2)

return

terminates execution of the method in which it appears and returns control to the calling method

throw

is used to signal the occurrence of an anomalous situation (exception) during the program execution Usually is used with try-catch or try-finally statements

Microsoft

64

Summary

Youve learned some basic features of C# such as how to use expressions and statements in C # You are also informed about value types, reference types as well as how to use variables in C# .

Microsoft

65

Anda mungkin juga menyukai