Chapter02 Core C# Programming Construct

Embed Size (px)

Citation preview

  • 7/27/2019 Chapter02 Core C# Programming Construct

    1/65

    Hoang Anh [email protected]

    HaNoi University of Technology

    1

    Chapter 2. Core C#

    Programming Constructs

  • 7/27/2019 Chapter02 Core C# Programming Construct

    2/65

    Microsoft

    Objectives

    This chapter surveys the C# language syntax. I introduceyou to the two fundamental kinds of types within theCLR: value types and reference types. This chapter alsodescribes namespaces and how you can use them tologically partition types and functionality within yourapplications.

    2

  • 7/27/2019 Chapter02 Core C# Programming Construct

    3/65

    Microsoft

    Roadmap

    2.1. C# Is a strongly Typed Language

    2.2. Expression

    2.3. Statements and Expressions2.4. Types and Variabless

    2.5. NameSpaces

    2.6. Control Flows

    3

  • 7/27/2019 Chapter02 Core C# Programming Construct

    4/65

    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 integersand returns the result

    4

  • 7/27/2019 Chapter02 Core C# Programming Construct

    5/65

    Microsoft

    double ComputeAvg( int param1, int param2 ){

    return (param1 + param2) / 2.0;}

    object ComputeAvg( object param1, object param2 )

    {

    return ((int) param1 + (int) param2) / 2.0;

    }

    ComputeAvg accepts two

    integers and returns a double. If

    passing an instance of Apple

    type, the compiler will complain

    and stop

    Convert objects into

    integers

    Passing an instance of

    Apple type causes an

    exception( the instance

    cant be convert into

    integer

    objectkeyword: an alias of

    System.Object class

    Object is not a numeric type

    5

  • 7/27/2019 Chapter02 Core C# Programming Construct

    6/65

    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

    6

  • 7/27/2019 Chapter02 Core C# Programming Construct

    7/65

    Microsoft

    2.2. Expressions

    Expressions in C# are identical to expressions in C++ andJava.

    Are built using operands, eg. variables or types within anapplication, 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 Example : OverandOver.csc

    C# operator precedence: When an expression contains multiple operators, theprecedence 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.

    7

  • 7/27/2019 Chapter02 Core C# Programming Construct

    8/65

    Microsoft

    Category Expression Description

    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 forT

    checked(x) Evaluate expression in checked context

    unchecked(x) Evaluate expression in unchecked contextdefault(T) Obtain default value of type T

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

    8

  • 7/27/2019 Chapter02 Core C# Programming Construct

    9/65

    Microsoft

    Category Expression DescriptionUnary +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

    xy Subtraction, delegate removal

    Shift x > y Shift right

    9

  • 7/27/2019 Chapter02 Core C# Programming Construct

    10/65

    Microsoft

    Category Expression DescriptionRelational and

    type testing

    x < y Less than

    x > y Greater than

    x = y Greater than or equal

    x is T Return true ifx is a T, false otherwisex as T Return x typed as T, ornull ifx 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 XORLogical OR x | y Integer bitwise OR, boolean logical OR

    10

  • 7/27/2019 Chapter02 Core C# Programming Construct

    11/65

    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

    11

  • 7/27/2019 Chapter02 Core C# Programming Construct

    12/65

    Microsoft

    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 }

    Declarat ion statements:are used to declare local variables andconstants

    12

    {x=69;y=96}

    int a;

    int b = 2, c = 3;

  • 7/27/2019 Chapter02 Core C# Programming Construct

    13/65

    Microsoft

    Statements and Expressions(2)

    Epression statementsare used to evaluate expressions

    Select ion statementsare used to select one of a number of

    possible statements for execution based on the value of someexpressionif, switch

    Iteration statement sare used to repeatedly execute an

    embedded statementwhile,do,for,foreach

    13

    while (i ++< Length) {

    Console.WriteLine(args[i]);

    }

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

    else {x=96;}

    Console.WriteLine(Goodbye);

  • 7/27/2019 Chapter02 Core C# Programming Construct

    14/65

    Microsoft

    Statements and Expressions(3)

    Jump statementsare used to transfer control -break,continue, goto, throw, return, andyield

    The try...catch statement is used to catch exceptions that

    occur during execution of a block, and the try...finallystatement is used to specify finalization code that is alwaysexecuted, whether an exception occurred or not

    14

    1. while (true) {

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

    4. Console.WriteLine(n);

    5. }

  • 7/27/2019 Chapter02 Core C# Programming Construct

    15/65

    Microsoft

    Statements and Expressions(4)

    The checkedand uncheckedstatements are used to control

    the overflow checking context for integral-type arithmeticoperations and conversions. Ex : Exam.csc

    Thelock

    statement is used to obtain the mutual-exclusion lock

    for a given object, execute a statement, and then release thelock

    The using statement is used to obtain a resource, execute a

    statement, and then dispose of that resource

    15

  • 7/27/2019 Chapter02 Core C# Programming Construct

    16/65

    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

    16

  • 7/27/2019 Chapter02 Core C# Programming Construct

    17/65

    Microsoft

    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 theyare boxed

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

    Reference types:

    Living place: on the heap Variables used to manipulate them are references to objects onthe managed heap

    17

  • 7/27/2019 Chapter02 Core C# Programming Construct

    18/65

    Microsoft

    Value Types

    Contain directly their value and are customarily created

    statically

    Initialization: using the newstatement

    Derive from System.ValueType

    Primitives: int, float, char and bool

    Others: enum, struct

    18

  • 7/27/2019 Chapter02 Core C# Programming Construct

    19/65

    Microsoft

    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

    19

  • 7/27/2019 Chapter02 Core C# Programming Construct

    20/65

    Microsoft

    Example:

    20

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

    s "Hello world"

    ValueType

    ReferenceType

    20

  • 7/27/2019 Chapter02 Core C# Programming Construct

    21/65

    Microsoft

    Value Types contain Reference Types

    Example:

    class ShapeInfo

    {

    public string infoString;

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

    }

    Reference type

    21

  • 7/27/2019 Chapter02 Core C# Programming Construct

    22/65

    Microsoft

    struct Rectangle{

    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);}

    }

    Value type

    The Rectangle structure

    contains a reference

    type member

    22

  • 7/27/2019 Chapter02 Core C# Programming Construct

    23/65

    Microsoft

    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 tor1

    Change some

    values of r2.

    Print values

    of both

    rectangles

    23

  • 7/27/2019 Chapter02 Core C# Programming Construct

    24/65

    Microsoft

    Result:

    24

  • 7/27/2019 Chapter02 Core C# Programming Construct

    25/65

    Microsoft

    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 thesame as the value computed by the value-types default

    constructor

    255

  • 7/27/2019 Chapter02 Core C# Programming Construct

    26/65

    Microsoft

    Default Variable Initialization(2)

    Value-types default constructor:

    All value types implicitly declare a public parameterless instance

    constructor called the defaul t con structor

    Default constructor returns the default valuefor the value type:

    26

    Value Type Default Value

    sbyte, byte, short, ushort, int, uint,

    long, and ulong

    0

    char '\x0000'

    26

  • 7/27/2019 Chapter02 Core C# Programming Construct

    27/65

    Microsoft

    Default Variable Initialization(3)

    27

    Value Type Default Value

    float 0.0f

    double 0.0d

    decimal 0.0m

    bool false

    enum-type E 0, converted to the type E

    struct-type All value type fields: default value ofValue Type

    All reference type fields: null

    27

  • 7/27/2019 Chapter02 Core C# Programming Construct

    28/65

    Microsoft

    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 betedious

    28

  • 7/27/2019 Chapter02 Core C# Programming Construct

    29/65

    Microsoft

    Implicitly Typed Local Variables(2)

    varis 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:

    varlocalVariant =

    localVariant is init with type of

    29

  • 7/27/2019 Chapter02 Core C# Programming Construct

    30/65

    Microsoft

    using System;

    using System.Collections.Generic;

    public class EntryPoint{

    static void Main()

    {

    var myList = new List();

    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

    30

  • 7/27/2019 Chapter02 Core C# Programming Construct

    31/65

    Microsoft

    Implicitly Typed Local Variables(3)

    Restriction:

    varcannot 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 local-

    variable-initializervar x; //Error, no initializer to infer type from

    The local-variable-initializermust be an expression

    The initializerexpression must have a compile-time typevar u = x => x + 1; //Error, anonymous functions do not have a type

    The initializerexpression cannot refer to the declared variable

    itself

    31

  • 7/27/2019 Chapter02 Core C# Programming Construct

    32/65

    Microsoft

    Type Conversion

    Many times, its necessary to convert intstances of one

    type to another

    Implicit Conversion:

    Explicit Conversion:

    int defaultValue = 12345678;

    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

  • 7/27/2019 Chapter02 Core C# Programming Construct

    33/65

    Microsoft

    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

    type

    33

    1. long x;

    2. int y = 25;

    3. x = y; //implicit numerical conversion

  • 7/27/2019 Chapter02 Core C# Programming Construct

    34/65

    Microsoft

    Implicit Conversions(2)

    Implicit Reference Conversion 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 animplicit 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

  • 7/27/2019 Chapter02 Core C# Programming Construct

    35/65

    Microsoft

    Implicit Conversions(3)

    Boxing Conversions

    Conversion of any value type to object type

    35

    1. int x = 10;

    2. object o = x; //Boxing

  • 7/27/2019 Chapter02 Core C# Programming Construct

    36/65

    Microsoft

    Explicit Conversions

    Using the casting operator()

    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

    36

    1. int x = (int) 26.45; //Explicit conversion

    2. Console.WriteLine(x); // Displays only 26

  • 7/27/2019 Chapter02 Core C# Programming Construct

    37/65

    Microsoft

    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.

    From any interface type I2 to any interface type I1, provided I2 isnot 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

  • 7/27/2019 Chapter02 Core C# Programming Construct

    38/65

    Microsoft

    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 theconversion 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

    The is operator only considers reference conversions, boxing

    conversions, and unboxing conversions38

  • 7/27/2019 Chapter02 Core C# Programming Construct

    39/65

    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

    39

  • 7/27/2019 Chapter02 Core C# Programming Construct

    40/65

    Microsoft

    1. public class List2. {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 List2. {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

    40

    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 boxed4. intList.Add(2); // Argument is boxed5. intList.Add("Three"); // Should be an error6.7. int i = (int)intList[0]; // Cast required

    1. ListintList = new List();2.3. intList.Add(1); // No boxing4. intList.Add(2); // No boxing5. intList.Add("Three"); // Compile-time error6.7. int i = intList[0]; // No cast required

  • 7/27/2019 Chapter02 Core C# Programming Construct

    41/65

    Microsoft

    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

    41

  • 7/27/2019 Chapter02 Core C# Programming Construct

    42/65

    Microsoft

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

    42

  • 7/27/2019 Chapter02 Core C# Programming Construct

    43/65

    Microsoft

    Generics(4)

    Type parameters can be applied to Class, struct, interface, and delegate types

    class Dictionary {...}

    struct Pair {...}

    interface IComparer {...}

    delegate ResType Func(ArgType

    arg);

    43

    DictionarycustomerLookupTable;

    DictionaryorderLookupTable;

    Dictionary numberSpellings;

  • 7/27/2019 Chapter02 Core C# Programming Construct

    44/65

    Microsoft

    1. class Array

    2. {3. publicstatic T[] Create(int size) {4. returnnew T[size];5. }6.7. public static void Sort(T[] array) {

    8. ...9. }10. }

    1. string[] names = Array.Create(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

    44

  • 7/27/2019 Chapter02 Core C# Programming Construct

    45/65

    Microsoft

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

    2.3. class Dictionary

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

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

    8. ...9. }10. }

    11. }

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

    2. class Dictionary where K: IComparable3. {

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

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

    8. }9. }10. }

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

    2.3. class Dictionary: IDictionary where4. K: IComparable,5. V: IKeyProvider,6. V: IPersistable,7. V: new()

    8. {9. ...10. }

    Generics(6)

    Constraints One base class, multiple interfaces, new()

    Specified using where clause

    45

  • 7/27/2019 Chapter02 Core C# Programming Construct

    46/65

    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

    46

  • 7/27/2019 Chapter02 Core C# Programming Construct

    47/65

    Microsoft

    2.5 Namespaces

    Need for Namespaces

    Using namespace directives

    Using alias directives

    Standard Namespaces in .NET

    47

  • 7/27/2019 Chapter02 Core C# Programming Construct

    48/65

    Microsoft

    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

  • 7/27/2019 Chapter02 Core C# Programming Construct

    49/65

    Microsoft

    Using namespace directives

    1. using System;

    2. classHello

    3. {

    4. static voidMain()

    5. {

    6. stringhello = Hello!;

    7. Console.WriteLine(hello);8. }

    9. }

    49

    Console is a class ofnamespace System.

    If not use using System; youmust use methodSystem.Console.WriteLine()to write hello

  • 7/27/2019 Chapter02 Core C# Programming Construct

    50/65

    Microsoft

    Using alias directives

    using identifier = namespace-or-type-name ;

    For example:

    50

    1. namespace N1.N2

    2. {3. classA {}

    4. }

    5. namespace N3

    6. {

    7. usingA = N1.N2.A;

    8. classB: A {}

    9. }

  • 7/27/2019 Chapter02 Core C# Programming Construct

    51/65

    Microsoft

    Standard Namespaces in .NET

    51

    Fundamentals

    System System.IO

    System.AddIn System.Linq

    System.Collections System.ReflectionSystem.ComponentModel System.Resources

    System.Configuration System.Runtime

    System.Diagnostics System.Security

    System.DirectoryServices System.ServiceProcessSystem.EnterpriseServices System.Text

    System.Globalization System.Threading

    System.IdentityModel.Claims System.Transactions

  • 7/27/2019 Chapter02 Core C# Programming Construct

    52/65

    Microsoft

    Standard Namespaces in .NET(2)

    Windows Presentation Foundation

    System.Windows

    Windows Forms

    System.Drawing System.Media

    System.Windows.Forms

    ASP.NET

    System.Web

    52

  • 7/27/2019 Chapter02 Core C# Programming Construct

    53/65

    Microsoft

    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

    53

  • 7/27/2019 Chapter02 Core C# Programming Construct

    54/65

    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

    54

  • 7/27/2019 Chapter02 Core C# Programming Construct

    55/65

    Microsoft

    2.6 Control Flow

    if-else, switch

    while, do-while, and for

    foreach

    break, continue, goto, return, and throw

    55

  • 7/27/2019 Chapter02 Core C# Programming Construct

    56/65

    Microsoft

    if-else construct

    if (condition)

    statement(s)_1 //The original result

    [else

    statement(s)_2] //The alternative result

    condi t ionis a relational or logical expression.

    statement(s)_1is a statement (or a block of statements) that is

    executed if the condition is true.

    statement(s)_2is a statement (or a block of statements) that is

    executed if the condition is false

    56

    1. if (salary > 2000)2. Console.Write("Salary is greater than 2k");

    1. if (salary > 2000)2. Console.Write("Salary is greater than 2k");

    //The original result3. else4. Console.Write("Salary is less than or equal

    to 2k"); // The alternative result

  • 7/27/2019 Chapter02 Core C# Programming Construct

    57/65

    Microsoft

    Nested if-else Statements

    if (condition_1)

    statement_1;

    else if (condition_2)

    statement_2;

    else if (condition_3)

    statement_3;

    ...else

    statement_n;

    57

  • 7/27/2019 Chapter02 Core C# Programming Construct

    58/65

    Microsoft

    switch (expression)

    {

    case constant-1: statement(s);

    jump-statementcase constant-2: statement(s);

    jump-statement

    case constant-3:

    ...

    [default: statement(s);jump-statement]

    }

    switch Constructexpression represents a valuethat corresponds to theassociated switch choice

    statement(s) is astatement orblock ofstatements that is

    executed if thecorrespondingcondition isevaluated true

    jump-statement is

    a branchingstatement totransfer controloutside the specificcase, such asbreak or goto(explained later)

    default dealswith all theother cases

    58

    1. using System;

    2. classSwitch

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

    15. }

  • 7/27/2019 Chapter02 Core C# Programming Construct

    59/65

    Microsoft

    while Loop

    while (control_expression)

    statement(s);

    control_expression is a condition be satisfied during

    the loop execution.

    statement(s) is a statement (or the block of statements)

    to be executed.

    59

    1. using System;2. classWhileLoop3. {4. static void Main()

    5. {6. int counter=0;7. while(counter++

  • 7/27/2019 Chapter02 Core C# Programming Construct

    60/65

    Microsoft

    do

    statement(s)

    while (control_expression);

    control_expression is a condition to be satisfied during

    the loop execution.

    statement(s) is a statement (or the block of statements)

    to be executed.

    60

    do-while Loop

    1. using System;2. classDoWhileLoop3. {4. static void Main()

    5. {6. int counter=0;7. do8. {9. Console.WriteLine(counter);

    10. }11. while(counter++

  • 7/27/2019 Chapter02 Core C# Programming Construct

    61/65

    Microsoft

    for Loop

    for ([initialization];[control_expression]; counter_update])statement(s)

    initialization is the counter initialization statement.

    control_expression is a condition to be satisfied during

    the loop execution.

    counter_update is the counter increment or decrement

    statement.

    statement(s) is the statement or block of statements to

    be repeated.

    61

    1. using System;2. classForLoop3. {4. static void Main()

    5. {6. for (int counter = 1;counter

  • 7/27/2019 Chapter02 Core C# Programming Construct

    62/65

    Microsoft

    The foreach Loop

    foreach (type identifier in expression)statement(s);

    type is the data type, such as int or string.

    identifieris the variable name.

    expression is the name of the array (or collection).

    statement(s) is the statement or block of statements to

    be executed.

    62

    1. using System;2. classForeachLoop3. {4. staticvoid Main()

    5. {6. int[,] myIntArray = {{1, 3, 5},7. {2, 4, 6} };8. foreach(int i in myIntArray)9. Console.Write("{0} ", i);

    10. }11. }

  • 7/27/2019 Chapter02 Core C# Programming Construct

    63/65

    Microsoft

    Branching Statements

    break

    terminates the closest enclosing loop or switch statement in

    which it appears

    goto: gotolabel;

    is not recommended because it corrupts the program structure

    gotocaseexpression; gotodefault; (in casestruct)

    continue passes control to the next iteration of the enclosing iteration

    statement in which it appears

    63

  • 7/27/2019 Chapter02 Core C# Programming Construct

    64/65

    Microsoft

    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

    64

  • 7/27/2019 Chapter02 Core C# Programming Construct

    65/65

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