Tải bản đầy đủ (.pdf) (65 trang)

this site is individual site for ueh students of information management faculty this site provides some students resources of it courses such as computer network data structure and algorithm enterprise resource planning

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (703.8 KB, 65 trang )

<span class='text_page_counter'>(1)</span><div class='page_container' data-page=1>

<b>Chapter 2. Core C# </b>



</div>
<span class='text_page_counter'>(2)</span><div class='page_container' data-page=2>

<b>Microsoft</b>


Objectives



<i>“This chapter surveys the C# language syntax. I introduce</i>


<i>you to the two fundamental kinds of types within the</i>


<i>CLR: value types and reference types. This chapter also</i>


<i>describes namespaces and how you can use them to</i>


<i>logically partition types and functionality within your</i>


<i>applications.”</i>



</div>
<span class='text_page_counter'>(3)</span><div class='page_container' data-page=3>

Roadmap



2.1. C# Is a strongly Typed Language



<i>2.2. Expression</i>



<i>2.3. Statements and Expressions</i>


<i>2.4. Types and Variabless</i>



</div>
<span class='text_page_counter'>(4)</span><div class='page_container' data-page=4>

<b>Microsoft</b>


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


</div>
<span class='text_page_counter'>(5)</span><div class='page_container' data-page=5>

<b>double ComputeAvg( int param1, int param2 )</b>
<b>{</b>


<b>return (param1 + param2) / 2.0;</b>
<b>}</b>


<b>object ComputeAvg( object param1, object param2 )</b>
<b>{</b>


<b>return ((int) param1 + (int) param2) / 2.0;</b>
<b>}</b>


<b>ComputeAvg accepts two </b>


<b>integers and returns a double. If </b>
<b>passing an instance of Apple </b>
<b>type, the compiler will complain </b>
<b>and stop</b>


<b>Convert objects into </b>
<b>integers</b>



<i>object</i><b>keyword: an alias of </b>
<b>System.Object class</b>


</div>
<span class='text_page_counter'>(6)</span><div class='page_container' data-page=6>

<b>Microsoft</b>


Roadmap



<i>2.1. C# Is a strongly Typed Language</i>



2.2. Expression



<i>2.3. Statements and Expressions</i>



<i>2.4. Types and Variabless</i>



<i>2.5. NameSpaces</i>



<i>2.6. Control Flows</i>



</div>
<span class='text_page_counter'>(7)</span><div class='page_container' data-page=7>

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



• Eg: the + operator can mean string concatenation using with string operands


C# operator precedence:



• When an expression contains multiple operators, the <i>precedence</i> of the
operators controls the order in which the individual operators are evaluated


• Entries at the top of the table have higher precedence


</div>
<span class='text_page_counter'>(8)</span><div class='page_container' data-page=8>

<b>Microsoft</b>


<b>Category</b> <b>Expression</b> <b>Description</b>
Primary x.m Member access


x(...) Method and delegate invocation


x[...] Array and indexer access


x++ Post-increment


x-- Post-decrement


new T(...) Object and delegate creation


new T(...){...} Object creation with initializer


new {...} Anonymous object initializer



new T[...] Array creation


typeof(T) Obtain System.Type object for T


checked(x) Evaluate expression in checked context


unchecked(x) Evaluate expression in unchecked context


default(T) Obtain default value of type T


delegate {...} Anonymous function (anonymous method)


</div>
<span class='text_page_counter'>(9)</span><div class='page_container' data-page=9>

<b>Category</b> <b>Expression</b> <b>Description</b>


Unary +x Identity


-x Negation


!x Logical negation


~x Bitwise negation


++x Pre-increment


--x Pre-decrement


(T)x Explicitly convert x to type T


Multiplicative x * y Multiplication



x / y Division


x % y Remainder


Additive x + y Addition, string concatenation, delegate combination


x – y Subtraction, delegate removal


Shift x << y Shift left


</div>
<span class='text_page_counter'>(10)</span><div class='page_container' data-page=10>

<b>Microsoft</b>


<b>Category</b> <b>Expression</b> <b>Description</b>
Relational and


type testing


x < y Less than
x > y Greater than


x <= y Less than or equal
x >= y Greater than or equal


x is T Return true if x is a T, false otherwise
x as T Return x typed as T, or null if x is not a T
Equality x == y Equal


x != y Not equal


Logical AND x & y Integer bitwise AND, boolean logical AND


Logical XOR x ^ y Integer bitwise XOR, boolean logical XOR
Logical OR x | y Integer bitwise OR, boolean logical OR


</div>
<span class='text_page_counter'>(11)</span><div class='page_container' data-page=11>

Roadmap



<i>2.1. C# Is a strongly Typed Language</i>



<i>2.2. Expression</i>



2.3. Statements and Expressions



<i>2.4. Types and Variabless</i>



<i>2.5. NameSpaces</i>



</div>
<span class='text_page_counter'>(12)</span><div class='page_container' data-page=12>

<b>Microsoft</b>


2.3 Statements and Expressions



The actions of a program are expressed using



<i><b>statements</b></i>



Several different kinds of statements:



 <b>A block: consists of a list of statements written between the </b>


<b>delimiters { and }</b>


 <i><b>Declaration statements: are used to declare local variables and </b></i>



constants


<b>12</b>


{x=69;y=96}


int a;


</div>
<span class='text_page_counter'>(13)</span><div class='page_container' data-page=13>

Statements and Expressions(2)



 <i><b>Epression statements are used to evaluate expressions</b></i>


 <i><b>Selection statements are used to select one of a number of </b></i>


possible statements for execution based on the value of some
expression – <b>if, switch</b>


 <i><b>Iteration statements are used to repeatedly execute an </b></i>


embedded statement – <b>while</b>, <b>do</b>, <b>for</b>, <b>foreach</b>


while (i ++< Length) {


if(continue == true) {x=69;}
else {x=96;}


</div>
<span class='text_page_counter'>(14)</span><div class='page_container' data-page=14>

<b>Microsoft</b>


Statements and Expressions(3)




 <i><b>Jump statements are used to transfer control -</b></i> <b>break, </b>


<b>continue, goto, throw, return, and yield</b>


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


<b>14</b>


1. while (true) {


2. int n = Console.Read();
3. if (n == 69) break;


4. Console.WriteLine(n);


</div>
<span class='text_page_counter'>(15)</span><div class='page_container' data-page=15>

Statements and Expressions(4)



 The <b>checked</b> and <b>unchecked</b> statements are used to control
the overflow checking context for integral-type arithmetic


operations and conversions


 The <b>lock</b> statement is used to obtain the mutual-exclusion lock
for a given object, execute a statement, and then release the
lock



</div>
<span class='text_page_counter'>(16)</span><div class='page_container' data-page=16>

<b>Microsoft</b>


Roadmap



<i>2.1. C# Is a strongly Typed Language</i>



<i>2.2. Expression</i>



<i>2.3. Statements and Expressions</i>



2.4. Types and Variabless



<i>2.5. NameSpaces</i>



<i>2.6. Control Flows</i>



</div>
<span class='text_page_counter'>(17)</span><div class='page_container' data-page=17>

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


Are copied by value by default when passed as parameters to
methods or assigned to other variables


Reference types:




Living place: on the heap


</div>
<span class='text_page_counter'>(18)</span><div class='page_container' data-page=18>

<b>Microsoft</b>


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



</div>
<span class='text_page_counter'>(19)</span><div class='page_container' data-page=19>

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



<b>Derive from System.Object and created with the</b>

<i>new</i>


keyword



</div>
<span class='text_page_counter'>(20)</span><div class='page_container' data-page=20>

<b>Microsoft</b>



Example:



<b>20</b>


int i = 123;


string s = "Hello world";
123


i


s <sub>"Hello world"</sub>


Value
Type


Reference
Type


</div>
<span class='text_page_counter'>(21)</span><div class='page_container' data-page=21>

Value Types contain Reference Types



Example:



<b>class </b>

<b>ShapeInfo</b>


<b>{</b>



<b>public string infoString;</b>



<b>public ShapeInfo(string info)</b>



<b>{ infoString = info; }</b>



<b>}</b>



</div>
<span class='text_page_counter'>(22)</span><div class='page_container' data-page=22>

<b>Microsoft</b>


<b>struct Rectangle</b>
<b>{</b>


<b>public ShapeInfo rectInfo;</b>


<b>public int rectTop, rectLeft, rectBottom, rectRight;</b>


<b>public Rectangle(string info, int top, int left, int bottom, int right)</b>
<b>{</b>


<b>rectInfo = new ShapeInfo(info);</b>


<b>rectTop = top; rectBottom = bottom;</b>
<b>rectLeft = left; rectRight = right;</b>


<b>}</b>


<b>public void Display()</b>
<b>{</b>


<b>Console.WriteLine("String = {0}, Top = {1}, Bottom = {2}," +</b>
<b>"Left = {3}, Right = {4}",</b>


<b>rectInfo.infoString, rectTop, rectBottom, rectLeft, rectRight);</b>


<b>}</b>


<b>}</b>


<b>Value type</b>


<b>The Rectangle structure </b>
<b>contains a reference </b>


<b>type member</b>


</div>
<span class='text_page_counter'>(23)</span><div class='page_container' data-page=23>

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;


.
r1.Display();


r2.Display();
Create the
first
Rectangle.


Assign a new
Rectangle to


r1


Change some
values of r2.


</div>
<span class='text_page_counter'>(24)</span><div class='page_container' data-page=24>

<b>Microsoft</b>


Result:



</div>
<span class='text_page_counter'>(25)</span><div class='page_container' data-page=25>

Default Variable Initialization



The following categories of variables are automatically


initialized to their default values:



 Static variables.


 Instance variables of class instances.


 Array elements.


<i>For a variable of a reference-type, the default value is </i>


null




</div>
<span class='text_page_counter'>(26)</span><div class='page_container' data-page=26>

<b>Microsoft</b>


Default Variable Initialization(2)



<i>Value-type’s default constructor:</i>



 All value types implicitly declare a public parameterless instance
<i><b>constructor called the default constructor</b></i>


 <i><b>Default constructor returns the default value for the value type:</b></i>


<b>26</b>


<b>Value Type</b> <b>Default Value</b>


<b>sbyte, byte, short, ushort, int, uint, </b>
<b>long, and ulong</b>


0


<b>char</b> '\x0000'


</div>
<span class='text_page_counter'>(27)</span><div class='page_container' data-page=27>

Default Variable Initialization(3)



<b>Value Type</b> <b>Default Value</b>


<b>float</b> 0.0f


<b>double</b> 0.0d



<b>decimal</b> 0.0m


<b>bool</b> false


<i>enum-type E</i> 0, converted to the type E


</div>
<span class='text_page_counter'>(28)</span><div class='page_container' data-page=28>

<b>Microsoft</b>


Implicitly Typed Local Variables



<i>“In C#, every variable declared in the code must have an</i>


<i>explicit type associated with it. But sometimes, when</i>


<i>writing code for strongly typed languages, the amount of</i>


<i>typing needed to declare such variables can be</i>


<i>tedious…”</i>



</div>
<span class='text_page_counter'>(29)</span><div class='page_container' data-page=29>

Implicitly Typed Local Variables(2)



<i>var</i>

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:




</div>
<span class='text_page_counter'>(30)</span><div class='page_container' data-page=30>

<b>Microsoft</b>


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


</div>
<span class='text_page_counter'>(31)</span><div class='page_container' data-page=31>

Implicitly Typed Local Variables(3)



Restriction:



 <i><b>var cannot use with multiple variable declarators</b></i>


<b>var</b> <b>x=69, y=9.6; //Error, Implicitly-typed local variables cannot have </b>


multiple declarators


 <i>Declarator implicitly typed local variables must include a </i>


<i>local-variable-initializer</i>


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


 <i>The local-variable-initializer must be an expression</i>


 <i>The initializer expression must have a compile-time type</i>


</div>
<span class='text_page_counter'>(32)</span><div class='page_container' data-page=32>

<b>Microsoft</b>



Type Conversion



Many times, it’s necessary to convert intstances of one



type to another



Implicit Conversion:



Explicit Conversion:



int defaultValue = 12345678;


<b>long value = defaultValue;</b>


int smallerValue = (int) value;


public class EntryPoint
{


static void Main()
{


int employeeID = 303;


object boxedID = employeeID;
employeeID = 404;


<b>int unboxedID = (int) boxedID;</b>


System.Console.WriteLine( employeeID.ToString()


);


System.Console.WriteLine( unboxedID.ToString() );
}


</div>
<span class='text_page_counter'>(33)</span><div class='page_container' data-page=33>

Implicit Conversions



One type of data is automatically converted into another


type of data



No data loss



Implicit Numerical Conversion



Implicit Enumeration Conversion



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


1. long x;


2. int y = 25;


</div>
<span class='text_page_counter'>(34)</span><div class='page_container' data-page=34>

<b>Microsoft</b>


Implicit Conversions(2)



<b>Implicit Reference Conversion</b>



 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.


</div>
<span class='text_page_counter'>(35)</span><div class='page_container' data-page=35>

Implicit Conversions(3)



<b>Boxing Conversions</b>



 Conversion of any value type to object type


1. int x = 10;



</div>
<span class='text_page_counter'>(36)</span><div class='page_container' data-page=36>

<b>Microsoft</b>


Explicit Conversions



<b>Using the casting operator ()</b>



May be loss data



Explicit Numerical Conversions



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


<b>36</b>


</div>
<span class='text_page_counter'>(37)</span><div class='page_container' data-page=37>

Explicit Conversions(2)



Explicit Reference Conversions



 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.


</div>
<span class='text_page_counter'>(38)</span><div class='page_container' data-page=38>

<b>Microsoft</b>


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


The is

operator



 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



 <b>The is operator only considers reference conversions, boxing </b>
conversions, and unboxing conversions


</div>
<span class='text_page_counter'>(39)</span><div class='page_container' data-page=39>

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:



</div>
<span class='text_page_counter'>(40)</span><div class='page_container' data-page=40>

<b>Microsoft</b>


1. public class List
2. {


3. private object[] elements;
4. private int count;


5.


6. public void Add(object element) {


7. if (count == elements.Length) Resize(count*2);
8. elements[count++] = element;


9. }



10.


11. public object this[int index] {
12. get { return elements[index]; }
13. set { elements[index] = value; }


14. }


15.


16. public int Count {


17. get { return count; }


18. }


19. }


1. public class List<ItemType>
2. {


3. private ItemType[] elements;
4. private int count;


5.


6. public void Add(ItemType element) {


7. if (count == elements.Length) Resize(count*2);
8. elements[count++] = element;



9. }


10.


11. public ItemType this[int index] {
12. get { return elements[index]; }
13. set { elements[index] = value; }


14. }


15.


16. public int Count {


17. get { return count; }


18. }


19. }


Generics



<b>40</b>


1. List intList = new List();
2.


3. intList.Add(1);
4. intList.Add(2);



5. intList.Add("Three");
6.


7. int i = (int)intList[0];
1. List intList = new List();
2.


3. intList.Add(1); // Argument is boxed
4. intList.Add(2); // Argument is boxed
5. intList.Add("Three"); // Should be an error
6.


7. int i = (int)intList[0]; // Cast required
1. List<int> intList = new List<int>();


2.


3. intList.Add(1); // No boxing
4. intList.Add(2); // No boxing


5. intList.Add("Three"); // Compile-time error
6.


</div>
<span class='text_page_counter'>(41)</span><div class='page_container' data-page=41>

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


</div>
<span class='text_page_counter'>(42)</span><div class='page_container' data-page=42>

<b>Microsoft</b>


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


</div>
<span class='text_page_counter'>(43)</span><div class='page_container' data-page=43>

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> {...}


delegate ResType Func<ArgType, ResType>(ArgType
arg);


Dictionary<string, Customer>
customerLookupTable;


</div>
<span class='text_page_counter'>(44)</span><div class='page_container' data-page=44>

<b>Microsoft</b>


1. class Array


2. {


3. public static T[] Create<T>(int size) {
4. return new T[size];


5. }


6.


7. public static void Sort<T>(T[] array) {
8. ...


9. }


10. }



1. string[] names = Array.Create<string>(3);
2. names[0] = "Jones";


3. names[1] = "Anderson";
4. names[2] = "Williams";
5. Array.Sort(names);


Generics(5)



Type parameters can be applied to



 Class, struct, interface, and delegate types


 Methods


</div>
<span class='text_page_counter'>(45)</span><div class='page_container' data-page=45>

1. interface IComparable{int CompareTo(object obj);}
2.


3. class Dictionary<K, V>
4. {


5. public void Add(K key, V value) {
6. ...


7. switch (((IComparable)key).CompareTo(x)) {


8. ...
9. }


10. }



1. interface IComparable{int CompareTo(object obj);}


2. class Dictionary<K, V> where K: IComparable


3. {


4. public void Add(K key, V value) {
5. ...


6. switch (key.CompareTo(x)) {


7. ...
8. }


9. }
10. }


1. interface IComparable<T> {int CompareTo(T obj);}
2.


3. class Dictionary<K, V>: IDictionary<K, V> where


4. K: IComparable<K>,


5. V: IKeyProvider<K>,


6. V: IPersistable,


7. V: new()



8. {


9. ...
10. }


Generics(6)



Constraints



 One base class, multiple interfaces, new()


</div>
<span class='text_page_counter'>(46)</span><div class='page_container' data-page=46>

<b>Microsoft</b>


Roadmap



<i>2.1. C# Is a strongly Typed Language</i>



<i>2.2. Expression</i>



<i>2.3. Statements and Expressions</i>



<i>2.4. Types and Variabless</i>



2.5. NameSpaces



<i>2.6. Control Flows</i>



</div>
<span class='text_page_counter'>(47)</span><div class='page_container' data-page=47>

2.5 Namespaces




Need for Namespaces



Using namespace directives



Using alias directives



</div>
<span class='text_page_counter'>(48)</span><div class='page_container' data-page=48>

<b>Microsoft</b>


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



<b>using keyword used to work with namespaces:</b>


 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).


</div>
<span class='text_page_counter'>(49)</span><div class='page_container' data-page=49>

Using namespace directives



<b>1.</b>

<b>using</b>

<b>System;</b>


<b>2.</b>

<b>class</b>

<b>Hello</b>




<b>3.</b>

<b>{</b>



<b>4.</b>

<b>static void </b>

<b>Main()</b>



<b>5.</b>

<b>{</b>



<b>6.</b>

<b>string</b>

<b>hello = “Hello!”;</b>



<b>7.</b>

<b>Console</b>

<b>.WriteLine(hello);</b>



<b>8.</b>

<b>}</b>



Console is a class of
namespace System.


</div>
<span class='text_page_counter'>(50)</span><div class='page_container' data-page=50>

<b>Microsoft</b>


Using alias directives



<b>using identifier = namespace-or-type-name ;</b>



For example:



<b>50</b>


1. namespace N1.N2


2. {



3. class A {}


4. }


5. namespace N3


6. {


7. using A = N1.N2.A;
8. class B: A {}


</div>
<span class='text_page_counter'>(51)</span><div class='page_container' data-page=51>

Standard Namespaces in .NET



<b>Fundamentals</b>


System System.IO


System.AddIn System.Linq


System.Collections System.Reflection


System.ComponentModel System.Resources


System.Configuration System.Runtime


System.Diagnostics System.Security


</div>
<span class='text_page_counter'>(52)</span><div class='page_container' data-page=52>

<b>Microsoft</b>


Standard Namespaces in .NET(2)




 Windows Presentation Foundation


 System.Windows


 Windows Forms


 System.Drawing


 System.Media


 System.Windows.Forms


 ASP.NET


 System.Web


</div>
<span class='text_page_counter'>(53)</span><div class='page_container' data-page=53>

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


</div>
<span class='text_page_counter'>(54)</span><div class='page_container' data-page=54>

<b>Microsoft</b>


Roadmap



<i>2.1. C# Is a strongly Typed Language</i>



<i>2.2. Expression</i>



<i>2.3. Statements and Expressions</i>



<i>2.4. Types and Variabless</i>



<i>2.5. NameSpaces</i>



2.6. Control Flows



</div>
<span class='text_page_counter'>(55)</span><div class='page_container' data-page=55>

2.6 Control Flow



if-else, switch



while, do-while, and for



foreach



</div>
<span class='text_page_counter'>(56)</span><div class='page_container' data-page=56>

<b>Microsoft</b>



if-else construct



<b>if (condition)</b>



<b>statement(s)_1 //</b>

<b>The original result</b>


<b>[else</b>



<b>statement(s)_2] //</b>

<b>The alternative result</b>


 <i><b>condition is a relational or logical expression.</b></i>


 <i><b>statement(s)_1 is a statement (or a block of statements) that is </b></i>


<i>executed if the condition is true.</i>


 <i><b>statement(s)_2 is a statement (or a block of statements) that is </b></i>


<i>executed if the condition is false</i>


<b>56</b>


1. if (salary > 2000)


2. Console.Write("Salary is greater than 2k");


1. if (salary > 2000)


2. Console.Write("Salary is greater than 2k");



<i>// The original result</i>


3. else


</div>
<span class='text_page_counter'>(57)</span><div class='page_container' data-page=57>

Nested if-else Statements



<b>if (condition_1)</b>


<b>statement_1;</b>



<b>else if (condition_2)</b>


<b>statement_2;</b>



<b>else if (condition_3)</b>


<b>statement_3;</b>



</div>
<span class='text_page_counter'>(58)</span><div class='page_container' data-page=58>

<b>Microsoft</b>


<b>switch (expression)</b>
<b>{</b>


<b>case constant-1: </b> <b>statement(s);</b>
<b>jump-statement</b>
<b>case constant-2: statement(s);</b>


<b>jump-statement</b>
<b>case constant-3:</b>
<b>...</b>
<b>[default: statement(s);</b>
<b>jump-statement]</b>


<b>}</b>


switch Construct

expression represents a value that corresponds to the
associated switch choice


statement(s) is a
statement or
block of


statements that is
executed if the
corresponding
condition is
evaluated true
jump-statement is
a branching
statement to
transfer control
outside the specific
case, such as


break or goto
(explained later)
default deals


with all the
other cases


<b>58</b>



1. using System;
2. class Switch


3. {


4. static void main()


5. {


6. int n = 2;


7. switch (n)


8. {


9. case 1: Console.WriteLine("n=1");


10. break;


11. default: Console.WriteLine("n=2");


12. break;


13. }


14. }


</div>
<span class='text_page_counter'>(59)</span><div class='page_container' data-page=59>

while Loop



<b>while (control_expression) </b>




<b>statement(s);</b>



<b>control_expression is a condition be satisfied during </b>



the loop execution.



<b>statement(s) is a statement (or the block of statements) </b>



to be executed.



1.

using

System;



2.

class

WhileLoop



3.

{



4.

static void

Main()



5.

{



6.

int

counter=0;



7.

while

(counter++ <= 10)



8.

{



9.

Console

.WriteLine(counter);



10.

}




11.

}



</div>
<span class='text_page_counter'>(60)</span><div class='page_container' data-page=60>

<b>Microsoft</b>


<b>do </b>



<b>statement(s) </b>



<b>while (control_expression);</b>



<b>control_expression is a condition to be satisfied during </b>



the loop execution.



<b>statement(s) is a statement (or the block of statements) </b>



to be executed.



<b>60</b>


do-while Loop



1.

using

System;



2.

class

DoWhileLoop



3.

{



4.

static void

Main()




5.

{



6.

int

counter=0;



7.

do



8.

{



9.

Console

.WriteLine(counter);



10.

}



11.

while

(counter++ <= 10);



12.

}



</div>
<span class='text_page_counter'>(61)</span><div class='page_container' data-page=61>

for Loop



<b>for ([initialization]; </b>



<b>[control_expression]; counter_update]) </b>


<b>statement(s)</b>



<b>initialization is the counter initialization statement.</b>



<b>control_expression is a condition to be satisfied during </b>



the loop execution.




<b>counter_update is the counter increment or decrement </b>



statement.



<b>statement(s) is the statement or block of statements to </b>



1.

using

System;



2.

class

ForLoop



3.

{



4.

static void

Main()



5.

{



6.

for

(

int

counter = 1;counter<=10;



counter=counter +2)



7.

{



8.

Console

.WriteLine(counter);



9.

}



10.

}



</div>
<span class='text_page_counter'>(62)</span><div class='page_container' data-page=62>

<b>Microsoft</b>



The foreach Loop



<b>foreach (type identifier in expression) </b>



<b>statement(s);</b>



<b>type is the data type, such as int or string.</b>



<b>identifier is the variable name.</b>



<b>expression is the name of the array (or collection).</b>



<b>statement(s) is the statement or block of statements to </b>



be executed.



<b>62</b>


1.

using

System;



2.

class

ForeachLoop



3.

{



4.

static void

Main()



5.

{



6.

int

[,] myIntArray = {{1, 3, 5},




7.

{2, 4, 6} };



8.

foreach

(

int

i

in

myIntArray)



9.

Console

.Write("{0} ", i);



10.

}



</div>
<span class='text_page_counter'>(63)</span><div class='page_container' data-page=63>

Branching Statements



break



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


goto:



 <b>goto</b> <b>label;</b>


 is not recommended because it corrupts the program structure


 <b>goto case</b> expression; <b>goto default</b>; (in case struct)

continue



</div>
<span class='text_page_counter'>(64)</span><div class='page_container' data-page=64>

<b>Microsoft</b>


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


</div>
<span class='text_page_counter'>(65)</span><div class='page_container' data-page=65>

Summary



You’ve learned some basic features of C# such as how



to use expressions and statements in C # …



</div>

<!--links-->

×