C# Tutorial - Basics

download C# Tutorial - Basics

of 127

Transcript of C# Tutorial - Basics

  • 8/12/2019 C# Tutorial - Basics

    1/127

    Introduction to C#The New Language for .

    H.Mssenbck

    University of Linz, Austria

    [email protected]

  • 8/12/2019 C# Tutorial - Basics

    2/127

    2

    Contents

    Advanced C#Introduction to C#

    1. Overview

    2. Types

    3. Expressions

    4. Declarations

    5. Statements

    6. Classes and Structs

    7. Inheritance

    8. Interfaces

    9. Delegates

    10. Exceptions

    11. Namespaces and Assemblies

    12. Attributes13. Threads

    14. XML Comments

    References:

    B.Albahari, P.Drayton, B.Merrill: C# Essentials. O'Reilly, 2001

    S.Robinson et al: Professional C#, Wrox Press, 2001

    Online documentation on the .NET SDK CD

  • 8/12/2019 C# Tutorial - Basics

    3/127

    3

    Features of C#

    Very similar to Java

    70% Java, 10% C++, 5% Visual Basic, 15% new

    As in Java

    Object-orientation (single inheritance)

    Interfaces Exceptions

    Threads

    Namespaces (like Packages)

    Strong typing Garbage Collection

    Reflection

    Dynamic loading of code

    ...

    As in C++

    (Operator) Overloading

    Pointer arithmetic in unsafe code Some syntactic details

  • 8/12/2019 C# Tutorial - Basics

    4/127

    4

    New Features in C#

    Really new (compared to Java)

    Reference and output parameters

    Objects on the stack (structs)

    Rectangular arrays

    Enumerations

    Unified type system

    goto

    Versioning

    "Syntactic Sugar"

    Component-based programming

    - Properties

    - Events

    Delegates

    Indexers

    Operator overloading

    foreach statements

    Boxing/unboxing

    Attributes

    ...

  • 8/12/2019 C# Tutorial - Basics

    5/127

    5

    Hello World

    File Hello.cs

    using System;

    class Hello {

    static void Main() {

    Console.WriteLine("Hello World");

    }

    }

    uses the namespace System

    entry point must be calledMain

    output goes to the console

    file name and class name

    need notbe identical

    Compilation (in the Console window)

    csc Hello.cs

    Execution

    Hello

  • 8/12/2019 C# Tutorial - Basics

    6/127

    6

    Structure of C# Programs

    Programm

    File F1.cs File F2.cs File F3.cs

    namespace A {...} namespace B {...} namespace C {...}

    class X {...} class Y {...} class Z {...}

    If no namespace is specified => anonymous default namespace

    Namespaces may also contain structs, interfaces, delegates and enums

    Namespace may be "reopened" in other files

    Simplest case: single class, single file, default namespace

  • 8/12/2019 C# Tutorial - Basics

    7/127

    7

    A Program Consisting of 2 Files

    Counter.cs

    Compilation

    csc Counter.cs Prog.cs

    => generates Prog.exe

    Execution

    Prog

    Working with DLLs

    csc /target:library Counter.cs=> generates Counter.dll

    csc /reference:Counter.dll Prog.cs

    => generates Prog.exe

    class Counter {

    int val = 0;

    public void Add (int x) { val = val + x; }

    public int Val () { return val; }}

    Prog.cs

    using System;

    class Prog {

    static void Main() {

    Counter c = new Counter();

    c.Add(3); c.Add(5);

    Console.WriteLine("val = " + c.Val());

    }

    }

  • 8/12/2019 C# Tutorial - Basics

    8/127

    Types

  • 8/12/2019 C# Tutorial - Basics

    9/127

    9

    Unified Type System

    Types

    Value Types Reference Types Pointers

    Enums Structs Classes Interfaces Arrays DelegatesSimple Types

    bool

    char

    sbyte

    short

    int

    long

    byte

    ushort

    uint

    ulong

    float

    double

    decimal User-defined Types

    All types are compatible with object- can be assigned to variables of type object

    - all operations of type objectare applicable to them

  • 8/12/2019 C# Tutorial - Basics

    10/127

    10

    Value Types versus Reference Types

    Value Types Reference Types

    variable contains value reference

    stored on stack heap

    initialisation 0, false, '\0' null

    assignment copies the value copies the reference

    exampleint i = 17; string s = "Hello";

    intj = i; string s1 = s;

    i 17 sH e l l o

    j 17 s1

  • 8/12/2019 C# Tutorial - Basics

    11/127

    11

    Simple Types

    Long Form in Java Range

    sbyte System.SByte byte -128 .. 127

    byte System.Byte --- 0 .. 255

    short System.Int16 short -32768 .. 32767

    ushort System.UInt16 --- 0 .. 65535

    int System.Int32 int -2147483648 .. 2147483647

    uint System.UInt32 --- 0 .. 4294967295

    long System.Int64 long -263 .. 263-1

    ulong System.UInt64 --- 0 .. 264-1

    float System.Single float 1.5E-45 .. 3.4E38 (32 Bit)

    double System.Double double 5E-324 .. 1.7E308 (64 Bit)decimal System.Decimal --- 1E-28 .. 7.9E28 (128 Bit)

    bool System.Boolean boolean true, false

    char System.Char char Unicode character

  • 8/12/2019 C# Tutorial - Basics

    12/127

    12

    Compatibility Between Simple Types

    decimal double float

    ulong uint ushort

    char

    long int short sbyte

    byteonly withtype cast

  • 8/12/2019 C# Tutorial - Basics

    13/127

    13

    Enumerations

    List of named constants

    Declaration (directly in a namespace)

    enum Color {red, blue, green} // values: 0, 1, 2

    enumAccess {personal=1, group=2, all=4}

    enumAccess1 : byte {personal=1, group=2, all=4}

    Use

    Color c = Color.blue; // enumeration constants must be qualified

    Access a = Access.personal | Access.group;

    if ((Access.personal & a) != 0) Console.WriteLine("access granted");

  • 8/12/2019 C# Tutorial - Basics

    14/127

    14

    Operations on Enumerations

    Compare if (c == Color.red) ...

    if (c > Color.red && c

  • 8/12/2019 C# Tutorial - Basics

    15/127

  • 8/12/2019 C# Tutorial - Basics

    16/127

    16

    Multidimensional Arrays

    Jagged (like in Java) a[0][1]

    a[0]

    a[1]

    a

    int[][] a = new int[2][];

    a[0] = new int[3];a[1] = new int[4];

    int x = a[0][1];

    int len = a.Length; // 2

    len = a[0].Length; // 3

    Rectangular (more compact, more efficient access)

    a[0, 1]int[,] a = new int[2, 3];

    int x = a[0, 1];

    int len = a.Length; // 6

    len = a.GetLength(0); // 2

    len = a.GetLength(1); // 3

    a

  • 8/12/2019 C# Tutorial - Basics

    17/127

    17

    Class System.String

    Can be used as standard typestring

    string s = "Alfonso";

    Note Strings are immutable (use StringBuilderif you want to modify strings)

    Can be concatenated with +: "Don " + s

    Can be indexed: s[i]

    String length: s.Length

    Strings are reference types => reference semantics in assignments

    but their values can be compared with == and != : if (s == "Alfonso") ...

    Class Stringdefines many useful operations:CompareTo, IndexOf, StartsWith, Substring, ...

  • 8/12/2019 C# Tutorial - Basics

    18/127

    18

    Structs

    Declaration

    struct Point {

    public int x, y; // fields

    public Point (int x, int y) { this.x = x; this.y = y; } // constructor

    public void MoveTo (int a, int b) { x = a; y = b; } // methods}

    Use

    Point p = new Point(3, 4); // constructor initializes object on the stack

    p.MoveTo(10, 20); // method call

  • 8/12/2019 C# Tutorial - Basics

    19/127

    19

    Classes

    Declaration

    class Rectangle {

    Point origin;

    public int width, height;

    public Rectangle() { origin = new Point(0,0); width = height = 0; }public Rectangle (Point p, int w, int h) { origin = p; width = w; height = h; }

    public void MoveTo (Point p) { origin = p; }

    }

    UseRectangle r = new Rectangle(new Point(10, 20), 5, 5);

    int area = r.width * r.height;

    r.MoveTo(new Point(3, 3));

  • 8/12/2019 C# Tutorial - Basics

    20/127

    20

    Differences Between Classes and Structs

    Classes

    Reference Types

    (objects stored on the heap)

    support inheritance

    (all classes are derived from object)

    can implement interfaces

    may have a destructor

    Structs

    Value Types

    (objects stored on the stack)

    no inheritance

    (but compatible with object)

    can implement interfaces

    no destructors allowed

  • 8/12/2019 C# Tutorial - Basics

    21/127

    21

    Boxing and Unboxing

    Value types (int, struct, enum) are also compatible with object!

    Boxing

    The assignmentobject obj = 3;

    wraps up the value 3 into a heap object

    UnboxingThe assignment

    int x = (int) obj;

    unwraps the value again

    obj

    3

  • 8/12/2019 C# Tutorial - Basics

    22/127

    22

    Boxing/Unboxing

    Allows the implementation of generic container types

    class Queue {

    ...

    public void Enqueue(object x) {...}

    public object Dequeue() {...}...

    }

    This Queue can then be used for reference types and value types

    Queue q = new Queue();

    q.Enqueue(new Rectangle());

    q.Enqueue(3);

    Rectangle r = (Rectangle) q.Dequeue();int x = (int) q.Dequeue();

  • 8/12/2019 C# Tutorial - Basics

    23/127

  • 8/12/2019 C# Tutorial - Basics

    24/127

    24

    Operators and their Priority

    Primary (x) x.y f(x) a[x] x++ x-- new typeof sizeof checked unchecked

    Unary + - ~ ! ++x --x (T)x

    Multiplicative * / %

    Additive + -

    Shift >

    Relational < > = is as

    Equality == !=

    Logical AND &

    Logical XOR ^

    Logical OR |

    Conditional AND &&

    Conditional OR ||

    Conditional c?x:y

    Assignment = += -= *= /= %= = &= ^= |=

    Operators on the same level are evaluated from left to right

  • 8/12/2019 C# Tutorial - Basics

    25/127

    25

    Overflow Check

    Overflow is not checked by default

    int x = 1000000;

    x = x * x; // -727379968, no error

    Overflow check can be turned on

    x = checked(x * x); // System.OverflowException

    checked {

    ...

    x = x * x; // System.OverflowException

    ...

    }

    Overflow check can also be turned on with a compiler switch

    csc /checked Test.cs

  • 8/12/2019 C# Tutorial - Basics

    26/127

  • 8/12/2019 C# Tutorial - Basics

    27/127

    Declarations

  • 8/12/2019 C# Tutorial - Basics

    28/127

    28

    Declaration Space

    The program area to which a declaration belongs

    Entities can be declared in a ...

    - namespace: Declaration of classes, interfaces, structs, enums, delegates- class, interface, struct: Declaration of fields, methods,properties, events, indexers, ...

    - enum: Declaration of enumeration constants

    - block: Declaration of local variables

    Scoping rules

    - A name must not be declared twice in the same declaration space.

    - Declarations may occur in arbitrary order.

    Exception: local variables must be declared before they are used

    Visibility rules

    - A name is only visible within its declaration space

    (local variables are only visible after their point of declaration).

    - The visibility can be restricted by modifiers (private, protected, ...)

  • 8/12/2019 C# Tutorial - Basics

    29/127

    29

    Namespaces

    File: X.cs

    File: Y.cs

    Equally named namespaces in different files constitute a single declaration space.

    Nested namespaces constitute a declaration space on their own.

    namespace A {

    ... Classes ...

    ... Interfaces ...

    ... Structs ...

    ... Enums ...

    ... Delegates ...

    }

    namespace B { // full name: A.B

    ...

    }

    namespace A {

    ...

    } namespace B {...}

    namespace C {...}

  • 8/12/2019 C# Tutorial - Basics

    30/127

  • 8/12/2019 C# Tutorial - Basics

    31/127

    31

    Blocks

    Various kinds of blocks

    void foo (int x) { // method block

    ... local variables ...

    { // nested block

    ... local variables ...

    }

    for (int i = 0; ...) { // structured statement block

    ... local variables ...}

    }

    Note The declaration space of a block includes the declaration spaces of nested blocks.

    Formal parameters belong to the declaration space of the method block.

    The loop variable in a for statement belongs to the block of the for statement.

    The declaration of a local variable must precede its use.

  • 8/12/2019 C# Tutorial - Basics

    32/127

    32

    Declaration of Local Variables

    void foo(int a) {

    int b;

    if (...) {

    int b; // error: b already declared in outer block

    int c; // ok so far, but wait ...

    int d;...

    } else {

    int a; // error: a already declared in outer block

    int d; // ok: no conflict with d from previous block

    }

    for (int i = 0; ...) {...}

    for (int i = 0; ...) {...} // ok: no conflict with i from previous loop

    int c; // error: c already declared in this declaration space

    }

  • 8/12/2019 C# Tutorial - Basics

    33/127

    Statements

  • 8/12/2019 C# Tutorial - Basics

    34/127

    34

    Simple Statements

    Empty statement

    ; // ; is a terminator, not a separator

    Assigment

    x = 3 * y + 1;

    Method call

    string s = "a,b,c";

    string[] parts = s.Split(','); // invocation of an object method (non-static)

    s = String.Join(" + ", parts); // invocation of a class method (static)

  • 8/12/2019 C# Tutorial - Basics

    35/127

    35

    if Statement

    if('0'

  • 8/12/2019 C# Tutorial - Basics

    36/127

    36

    switch Statement

    switch (country) {

    case "Germany": case "Austria": case "Switzerland":

    language = "German";

    break;

    case "England": case "USA":

    language = "English";break;

    case null:

    Console.WriteLine("no country specified");

    break;

    default:

    Console.WriteLine("don't know language of {0}", country);

    break;

    }

    Type of switch expression

    numeric, char, enum or string (null ok as a case label).

    No fall-through!

    Every statement sequence in a case must be terminated with break (or return, goto, throw).

    If no case label matches default

    If no default specified continuation after the switch statement

  • 8/12/2019 C# Tutorial - Basics

    37/127

    37

    switch with Gotos

    1

    E.g. for the implementation of automata

    int state = 0;

    int ch = Console.Read();

    switch (state) {

    case 0: if (ch == 'a') { ch = Console.Read(); goto case 1; }else if (ch == 'c') goto case 2;

    else goto default;

    case 1: if (ch == 'b') { ch = Console.Read(); goto case 1; }

    else if (ch == 'c') goto case 2;

    else goto default;

    case 2: Console.WriteLine("input valid");break;

    default: Console.WriteLine("illegal character {0}", ch);

    break;

    }

    b

    a c0 2

    c

  • 8/12/2019 C# Tutorial - Basics

    38/127

    38

    Loops

    while

    while (i < n) {

    sum += i;

    i++;

    }

    do while

    do {

    sum += a[i];i--;

    } while (i > 0);

    for Short form for

    for(int i = 0; i < n; i++) int i = 0;

    sum += i; while (i < n) {

    sum += i;

    i++;

    }

  • 8/12/2019 C# Tutorial - Basics

    39/127

  • 8/12/2019 C# Tutorial - Basics

    40/127

    40

    Jumps

    break; For exiting a loop or a switch statement.

    There is no break with a label like in Java (usegoto instead).

    continue; Continues with the next loop iteration.

    goto case 3: Can be used in a switch statement to jump to a case label.

    myLab:

    ...

    goto myLab; Jumps to the label myLab.

    Restrictions:

    - no jumps into a block

    - no jumps out of a finally block of a try statement

    S

  • 8/12/2019 C# Tutorial - Basics

    41/127

    41

    return Statement

    Returning from a void method

    void f(int x) {

    if (x == 0) return;

    ...}

    Returning a value from a function method

    int max(int a, int b) {

    if (a > b) return a; else return b;

    }

    class C {

    static int Main() {...

    return errorCode; // The Main method can be declared as a function;

    } // the returned error code can be checked with the

    // DOS variable errorlevel

    }

  • 8/12/2019 C# Tutorial - Basics

    42/127

    Classes and Structs

    C t t f Cl St t

  • 8/12/2019 C# Tutorial - Basics

    43/127

    43

    Contents of Classes or Structs

    class C {

    ... fields, constants ... // for object-oriented programming

    ... methods ...

    ... constructors, destructors ...

    ... properties ... // for component-based programming

    ... events ...

    ... indexers ... // for amenity

    ... overloaded operators ...

    ... nested types (classes, interfaces, structs, enums, delegates) ...

    }

  • 8/12/2019 C# Tutorial - Basics

    44/127

  • 8/12/2019 C# Tutorial - Basics

    45/127

    Visibility Modifiers (excerpt)

  • 8/12/2019 C# Tutorial - Basics

    46/127

    46

    Visibility Modifiers (excerpt)

    public visible where the declaring namespace is known

    - Members of interfaces and enumerations are public by default.

    - Types in a namespace (classes, structs, interfaces, enums, delegates)

    have default visibility internal(visible in the declaring assembly)

    private only visible in declaring class or struct

    - Members of classes and structs are private by default

    (fields, methods, properties, ..., nested types)

    Example

    public class Stack {

    private int[] val; // private is also default

    private int top; // private is also default

    public Stack() {...}

    public void Push(int x) {...}

    public int Pop() {...}

    }

    Fields and Constants

  • 8/12/2019 C# Tutorial - Basics

    47/127

    47

    Fields and Constants

    class C {

    int value = 0; Field- Initialization is optional- Initialization must not access other fields or methods

    of the same type- Fields of a struct must not be initialized

    const long size = ((long)int.MaxValue + 1) / 4;

    Constant

    - Value must be computable at compile time

    readonly DateTime date;

    Read Only Field- Must be initialized in their declaration or in a constructor

    - Value needs not be computable at compile time- Consumes a memory location (like a field)

    }

    Access within C Access from other classes... value ... size ... date ... C c = new C();

    ... c.value ... c.size ... c.date ...

    Static Fields and Constants

  • 8/12/2019 C# Tutorial - Basics

    48/127

    48

    Static Fields and Constants

    Belong to a class, not to an object

    class Rectangle {

    static Color defaultColor; // once per class

    static readonly int scale; // -- "

    // static constants are not allowedint x, y, width,height; // once per object

    ...

    }

    Access within the class Access from other classes

    ... defaultColor ... scale ... ... Rectangle.defaultColor ... Rectangle.scale ...

    Methods

  • 8/12/2019 C# Tutorial - Basics

    49/127

    49

    Methods

    Examples

    class C {

    int sum = 0, n = 0;

    public void Add (int x) { // proceduresum = sum + x; n++;

    }

    public float Mean() { // function (must return a value)

    return (float)sum / n;

    }

    }

    Access within the class Access from other classes

    this.Add(3); C c = new C();

    float x = Mean(); c.Add(3);

    float x = c.Mean();

    Static Methods

  • 8/12/2019 C# Tutorial - Basics

    50/127

    50

    Static Methods

    Operations on class data (static fields)

    class Rectangle {

    static Color defaultColor;

    public static void ResetColor() {

    defaultColor = Color.white;

    }

    }

    Access within the class Access from other classes

    ResetColor(); Rectangle.ResetColor();

    Parameters

  • 8/12/2019 C# Tutorial - Basics

    51/127

    51

    Parameters

    - "call by value"

    - formal parameter is a copy of the

    actual parameter

    - actual parameter is an expression

    Value Parameters (input values)

    void Inc(int x) {x = x + 1;}

    void f() {

    int val = 3;

    Inc(val); // val == 3

    }

    ref Parameters (transition values)

    void Inc(refint x) { x = x + 1; }

    void f() {

    int val = 3;

    Inc(refval); // val == 4

    }

    out Parameters (output values)

    void Read (out int first, out int next) {first = Console.Read(); next = Console.Read();

    }

    void f() {

    int first, next;

    Read(out first, out next);}

    - "call by reference"

    - formal parameter is an alias for the

    actual parameter

    (address of actual parameter is passed)- actual parameter must be a variable

    - similar to ref parametersbut no value is passed by the caller.

    - must not be used in the method before

    it got a value.

    Variable Number of Parameters

  • 8/12/2019 C# Tutorial - Basics

    52/127

    52

    Variable Number of Parameters

    Last n parameters may be a sequence of values of a certain type.

    void Add (out int sum, params int[] val) {

    sum = 0;

    foreach (int i in val) sum = sum + i;

    }

    params cannot be used for refand outparameters

    Use

    Add(out sum, 3, 5, 2, 9); // sum == 19

    keyword

    paramsarray type

    Method Overloading

  • 8/12/2019 C# Tutorial - Basics

    53/127

    53

    Method Overloading

    Methods of a class may have the same name- if they have different numbers of parameters, or

    - if they have different parameter types, or

    - if they have different parameter kinds (value, ref/out)

    Examplesvoid F (int x) {...}

    void F (char x) {...}

    void F (int x, long y) {...}

    void F (long x, int y) {...}

    void F (ref int x) {...}

    Callsint i; long n; short s;

    F(i); // F(int x)

    F('a'); // F(char x)F(i, n); // F(int x, long y)

    F(n, s); // F(long x, int y);

    F(i, s); // cannot distinguish F(int x, long y) and F(long x, int y); => compilation error

    F(i, i); // cannot distinguish F(int x, long y) and F(long x, int y); => compilation error

    Overloaded methods must not differ only in their function types, in the presence ofparamsor in refversus out!

    Constructors for Classes

  • 8/12/2019 C# Tutorial - Basics

    54/127

    54

    Constructors for Classes

    Example

    class Rectangle {

    int x, y, width, height;

    public Rectangle (int x, int y, int w, int h) {this.x = x; this.y = y; width = x; height = h; }

    public Rectangle (int w, int h) : this(0, 0, w, h) {}public Rectangle () : this(0, 0, 0, 0) {}

    ...

    }

    Rectangle r1 = new Rectangle();Rectangle r2 = new Rectangle(2, 5);

    Rectangle r3 = new Rectangle(2, 2, 10, 5);

    Constructors can be overloaded.

    A construcor may call another constructor with this

    (specified in the constructor head, not in its body as in Java!).

    Before a construcor is called, fields are possibly initialized.

    Default Constructor

  • 8/12/2019 C# Tutorial - Basics

    55/127

    55

    Default Constructor

    If no constructor was declared in a class, the compiler generates a

    parameterless default constructor:

    class C { int x; }

    C c = new C(); // ok

    The default constructor initializes all fields as follows:

    numeric 0

    enum 0

    bool false

    char '\0'reference null

    If a constructor was declared, no default constructor is generated:

    class C {

    int x;

    public C(int y) { x = y; }

    }

    C c1 = new C(); // compilation error

    C c2 = new C(3); // ok

    Constructors for Structs

  • 8/12/2019 C# Tutorial - Basics

    56/127

    56

    Constructors for Structs

    Example

    struct Complex {

    double re, im;

    public Complex(double re, double im) { this.re = re; this.im = im; }

    public Complex(double re) : this (re, 0) {}...

    }

    Complex c0; // c0.re and c0.im are still uninitialized

    Complex c1 = new Complex(); // c1.re == 0, c1.im == 0

    Complex c2 = new Complex(5); // c2.re == 5, c2.im == 0Complex c3 = new Complex(10, 3); // c3.re == 10, c3.im == 3

    For every struct the compiler generates a parameterless default constructor

    (even if there are other constructors).The default constructor zeroes all fields.

    Programmers must not declare a parameterless constructor for structs

    (for implementation reasons of the CLR).

  • 8/12/2019 C# Tutorial - Basics

    57/127

  • 8/12/2019 C# Tutorial - Basics

    58/127

    Properties

  • 8/12/2019 C# Tutorial - Basics

    59/127

    59

    p

    Syntactic sugar for get/set methods

    class Data {

    FileStream s;

    public string FileName {set {

    s = new FileStream(value, FileMode.Create);

    }

    get {

    return s.Name;

    }}

    }

    Used as "smart fields"Data d = new Data();

    d.FileName = "myFile.txt"; // invokes set("myFile.txt")

    string s = d.FileName; // invokes get()

    JIT compilers often inline get/set methods no efficiency penalty

    property typeproperty name

    "input parameter"

    of the set method

    Properties (continued)

  • 8/12/2019 C# Tutorial - Basics

    60/127

    60

    p ( )

    get or set can be omitted

    class Account {

    long balance;

    public long Balance {get { return balance; }

    }

    }

    x = account.Balance; // ok

    account.Balance = ...; // compilation error

    Why are properties a good idea?

    Interface and implementation of data may differ.

    Allows read-only and write-only fields.

    Can validate a field when it is assigned.

    Substitute for fields in interfaces.

    Indexers

  • 8/12/2019 C# Tutorial - Basics

    61/127

    61

    Programmable operator for indexing a collection

    class File {FileStream s;

    public int this [int index] {get { s.Seek(index, SeekOrigin.Begin);

    return s.ReadByte();}

    set { s.Seek(index, SeekOrigin.Begin);s.WriteByte((byte)value);

    }}

    }

    Use

    File f = ...;int x = f[10]; // calls f.get(10)

    f[10] = 'A'; // calls f.set(10, 'A')

    get or set method can be omitted (write-only / read-only)

    Indexers can be overloaded with different index types

    type and name

    of the index value

    name

    (always this)

    type of the

    indexed expression

    Indexers (other example)

  • 8/12/2019 C# Tutorial - Basics

    62/127

    62

    class MonthlySales {int[] product1 = new int[12];

    int[] product2 = new int[12];

    ...

    public int this[int i] { // set method omitted => read-only

    get { return product1[i-1] + product2[i-1]; }}

    public int this[string month] { // overloaded read-only indexer

    get {

    switch (month) {

    case "Jan": return product1[0] + product2[0];case "Feb": return product1[1] + product2[1];

    ...

    }

    }

    }

    }

    MonthlySales sales = new MonthlySales();

    ...

    Console.WriteLine(sales[1] + sales["Feb"]);

  • 8/12/2019 C# Tutorial - Basics

    63/127

    Conversion Operators

  • 8/12/2019 C# Tutorial - Basics

    64/127

    64

    Implicit conversion- If the conversion is always possible without loss of precision

    - e.g. long = int;

    Explicit conversion- If a run time check is necessary or truncation is possible

    - e.g. int = (int) long;

    Conversion operators for custom types

    class Fraction {

    int x, y;

    ...

    public static implicit operatorFraction (int x) { return new Fraction(x, 1); }

    public static explicit operatorint (Fraction f) { return f.x / f.y; }

    }

    Use

    Fraction f = 3; // implicit conversion, f.x == 3, f.y == 1

    int i = (int) f; // explicit conversion, i == 3

    Nested Types

  • 8/12/2019 C# Tutorial - Basics

    65/127

    65

    classA {int x;

    B b = new B(this);

    public void f() { b.f(); }

    }

    class C {

    A a = new A();

    A.B b = new A.B(a);

    }

    For auxiliary classes that should be hidden

    - Inner class can access all members of the outer class (even private members).

    - Outer class can access only public members of the inner class.

    - Other classes can access an inner class only if it is public.

    Nested types can also be structs, enums, interfaces and delegates.

    public class B {

    A a;public B(A a) { this.a = a; }

    public void f() { a.x = ...; ... a.f(); }

    }

  • 8/12/2019 C# Tutorial - Basics

    66/127

    1

    Advanced C#

    H.Mssenbck

    University of Linz, Austria

    [email protected]

    Contents Inheritance

    Interfaces

    Delegates

    Exceptions

    Namespaces and Assemblies

    Attributes

    Threads

    XML Comments

  • 8/12/2019 C# Tutorial - Basics

    67/127

    2

    Inheritance

    Syntax

  • 8/12/2019 C# Tutorial - Basics

    68/127

    3

    class A { // base classint a;

    public A() {...}

    public void F() {...}

    }

    class B: A { // subclass (inherits fromA, extendsA)

    int b;

    public B() {...}

    public void G() {...}

    }

    B inherits a andF(), it adds b and G()

    - constructors are not inherited

    - inherited methods can be overridden (see later)

    Single inheritance: a class can only inherit from one base class, but it can implement

    multiple interfaces.

    A class can only inherit from a class, not from a struct.

    Structs cannot inherit from another type, but they can implement multiple interfaces.

    A class without explicit base class inherits from object.

    Asignments and Type Checks

  • 8/12/2019 C# Tutorial - Basics

    69/127

    4

    class A {...}class B : A {...}

    class C: B {...}

    Assignments

    A a = new A(); // static type of a: the type specified in the declaration (hereA)

    // dynamic type of a: the type of the object in a (here alsoA)

    a = new B(); // dynamic type of a is B

    a = new C(); // dynamic type of a is C

    B b = a; // forbidden; compilation error

    Run time type checks

    a = new C();

    if (a is C) ... // true, if dynamic type of a is Cor a subclass; otherwise false

    if (a is B) ... // trueif (a is A) ... // true, but warning because it makes no sense

    a = null;

    if (a is C) ... // false: if a == null, a is Talways returns false

    Checked Type Casts

  • 8/12/2019 C# Tutorial - Basics

    70/127

    5

    Cast

    A a = new C();

    B b = (B) a; // if (a is B) stat.type(a) is B in this expression; else exception

    C c = (C) a;

    a = null;c = (C) a; // ok null can be casted to any reference type

    as

    A a = new C();

    B b = a as B; // if (a is B) b = (B)a; else b = null;

    C c = a as C;

    a = null;

    c = a as C; // c == null

    Overriding of Methods

  • 8/12/2019 C# Tutorial - Basics

    71/127

    6

    Only methods that are declared as virtual can be overridden in subclasses

    class A {

    public void F() {...} // cannot be overridden

    public virtual void G() {...} // can be overridden in a subclass

    }

    Overriding methods must be declared as override

    class B : A {

    public void F() {...} // warning: hides inherited F()

    use newpublic void G() {...} // warning: hides inherited G() use new

    public override void G() { // ok: overrides inherited G

    ... base.G(); // calls inherited G()

    }

    }

    Method signatures must be identical

    - same number and types of parameters (including function type)

    - same visibility (public, protected, ...).

    Properties and indexers can also be overridden (virtual, override).

    Static methods cannot be overridden.

    Dynamic Binding (simplified)

  • 8/12/2019 C# Tutorial - Basics

    72/127

    7

    class A {public virtual void WhoAreYou() { Console.WriteLine("I am an A"); }

    }

    class B : A {

    public override void WhoAreYou() { Console.WriteLine("I am a B"); }

    }

    A message invokes the method belonging to the dynamic type of the receiver

    (not quite true, see later)

    A a = new B();a.WhoAreYou(); // "I am a B"

    Every method that can work withA can also work withB

    void Use (A x) {x.WhoAreYou();

    }

    Use(new A()); // "I am an A"

    Use(new B()); // "I am a B"

    Hiding

  • 8/12/2019 C# Tutorial - Basics

    73/127

    8

    Members can be declared as new in a subclass.

    They hide inherited members with the same name.

    class A {

    public int x;public void F() {...}

    public virtual void G() {...}

    }

    class B : A {

    public new int x;public new void F() {...}

    public new void G() {...}

    }

    B b = new B();b.x = ...; // accesses B.x

    b.F(); ... b.G(); // calls B.F and B.G

    ((A)b).x = ...; // accesses A.x !

    ((A)b).F(); ... ((A)b).G(); // calls A.F and A.G !

    Dynamic Binding (with hiding)

  • 8/12/2019 C# Tutorial - Basics

    74/127

    9

    class A {public virtual void WhoAreYou() { Console.WriteLine("I am an A"); }

    }

    class B : A {

    public override void WhoAreYou() { Console.WriteLine("I am a B"); }

    }

    class C : B {

    public new virtual void WhoAreYou() { Console.WriteLine("I am a C"); }

    }

    class D : C {

    public override void WhoAreYou() { Console.WriteLine("I am a D"); }

    }

    C c = new D();c.WhoAreYou(); // "I am a D"

    A a = new D();

    a.WhoAreYou(); // "I am a B" !!

    Fragile Base Class Problem

  • 8/12/2019 C# Tutorial - Basics

    75/127

    10

    Initial situation

    class LibraryClass {

    public void CleanUp() { ... }

    }

    class MyClass : LibraryClass {

    public void Delete() { ... erase the hard disk... }}

    Later: vendor ships new version ofLibraryClass

    class LibraryClass {string name;

    public virtual void Delete() { name = null; }

    public void CleanUp() { Delete(); ... }

    }

    In Java the call myObj.CleanUp() would erase the hard disk!

    In C# nothing happens, as long asMyClass is not recompiled.

    MyClass still relies on the old version ofLibraryClass (Versioning)

    old CleanUp() does not callLibraryClass.Delete().

    IfMyClass is recompiled, the compiler forcesDelete to be declared as new or override.

  • 8/12/2019 C# Tutorial - Basics

    76/127

    Visibilityprotected and internal

  • 8/12/2019 C# Tutorial - Basics

    77/127

    12

    protected Visible in declaring class and its subclasses(more restricive than in Java)

    internal Visible in declaring assembly (see later)

    protected internal Visible in declaring class, its subclasses and the declaring assembly

    Example

    class Stack {protected int[] values = new int[32];protected int top = -1;

    public void Push(int x) {...}public int Pop() {...}

    }class BetterStack : Stack {

    public bool Contains(int x) {foreach (int y in values) if (x == y) return true;

    return false;}

    }class Client {

    Stack s = new Stack();... s.values[0] ... // compilation error!

    }

    Abstract Classes

  • 8/12/2019 C# Tutorial - Basics

    78/127

    13

    Example

    abstract class Stream {

    public abstract void Write(char ch);

    public void WriteString(string s) { foreach (char ch in s) Write(s); }

    }

    class File : Stream {

    public override void Write(char ch) {... write ch to disk...}

    }

    Note

    Abstract methods do not have an implementation.

    Abstract methods are implicitly virtual.

    If a class has abstract methods it must be declared abstractitself.

    One cannot create objects of an abstract class.

    Abstract Properties and Indexers

  • 8/12/2019 C# Tutorial - Basics

    79/127

    14

    Example

    abstract class Sequence {

    public abstract void Add(object x); // method

    public abstract string Name { get; } // property

    public abstract object this [int i] { get; set; } // indexer }

    class List : Sequence {

    public override void Add(object x) {...}

    public override string Name { get {...} }public override object this [int i] { get {...} set {...} }

    }

    Note

    Overridden indexers and properties must have the same get and set methods as in the

    base class

    Sealed Classes

  • 8/12/2019 C# Tutorial - Basics

    80/127

    15

    Example

    sealed class Account : Asset {

    long val;

    public void Deposit (long x) { ... }

    public void Withdraw (long x) { ... }...

    }

    Note sealedclasses cannot be extended (same asfinalclasses in Java),

    but they can inherit from other classes.

    override methods can be declared assealedindividually.

    Reason: Security (avoids inadvertent modification of the class semantics)

    Efficiency (methods can possibly be called using static binding)

  • 8/12/2019 C# Tutorial - Basics

    81/127

    16

    Interfaces

    Syntax

  • 8/12/2019 C# Tutorial - Basics

    82/127

    17

    public interface IList : ICollection, IEnumerable {int Add (object value); // methods

    bool Contains (object value);

    ...

    bool IsReadOnly { get; } // property

    ...

    object this [int index] { get; set; } // indexer

    }

    Interface = purely abstract class; only signatures, no implementation.

    May contain methods,properties, indexers and events

    (no fields, constants, constructors, destructors, operators, nested types).

    Interface members are implicitlypublic abstract(virtual).

    Interface members must not bestatic.

    Classes and structs may implement multiple interfaces.

    Interfaces can extend other interfaces.

    Implemented by Classes and Structs

  • 8/12/2019 C# Tutorial - Basics

    83/127

    18

    class MyClass : MyBaseClass, IList, ISerializable {public int Add (object value) {...}

    public bool Contains (object value) {...}

    ...

    public bool IsReadOnly { get {...} }

    ...

    public object this [int index] { get {...} set {...} }

    }

    A class can inherit from asingle base class, but implement multiple interfaces.

    A struct cannot inherit from any type, but can implement multiple interfaces.

    Every interface member (method, property, indexer) must be implementedor inherited

    from a base class.

    Implemented interface methods must notbe declared as override.

    Implemented interface methods can be declared virtualor abstract(i.e. an interface can

    be implemented by an abstract class).

    Working with Interfaces

  • 8/12/2019 C# Tutorial - Basics

    84/127

    19

    Assignments: MyClass c = new MyClass();

    IList list = c;

    Method calls: list.Add("Tom"); // dynamic binding => MyClass.Add

    Type checks: if (list is MyClass) ... // true

    Type casts: c = list as MyClass;

    c = (MyClass) list;

    ISerializable ser = (ISerializable) list;

    MyClass

    MyBaseClass

    IList ISerializable

    Example

  • 8/12/2019 C# Tutorial - Basics

    85/127

    20

    interface ISimpleReader{int Read();

    }

    interface IReader: ISimpleReader {void Open(string name);

    void Close();}

    class Terminal : ISimpleReader {public int Read() { ... }

    }

    class File : IReader {public int Read() { ... }public void Open(string name) { ... }public void Close() { ... }

    }

    ISimpleReader sr = null; // null can be assigned to any interface variablesr = new Terminal();sr = new File();

    IReader r = new File();sr = r;

    Terminal

    Read

    ISimpleReader

    Read

    File

    Read

    Open

    Close

    IReader

    Open

    Close

  • 8/12/2019 C# Tutorial - Basics

    86/127

    21

    Delegates and Events

    Delegate = Method Type

    D l i f d l

  • 8/12/2019 C# Tutorial - Basics

    87/127

    22

    Declaration of a delegate type

    delegate void Notifier (string sender); // ordinary method signature

    // with the keyword delegate

    Declaration of a delegate variableNotifier greetings;

    Assigning a method to a delegate variable

    void SayHello(string sender) {Console.WriteLine("Hello from " + sender);

    }

    greetings = new Notifier(SayHello);

    Calling a delegate variable

    greetings("John"); // invokes SayHello("John") => "Hello from John"

    Assigning Different Methods

    E t hi th d b i d t d l t i bl

  • 8/12/2019 C# Tutorial - Basics

    88/127

    23

    Every matching method can be assigned to a delegate variable

    void SayGoodBye(string sender) {

    Console.WriteLine("Good bye from " + sender);

    }

    greetings = new Notifier(SayGoodBye);

    greetings("John"); // SayGoodBye("John") => "Good bye from John"

    Note A delegate variable can have the value null(no method assigned).

    If null, a delegate variable must not be called (otherwise exception).

    Delegate variables are first class objects: can be stored in a data structure, passed as

    parameter, etc.

    Creating a Delegate Value

    D l t T ( bj M th d)

  • 8/12/2019 C# Tutorial - Basics

    89/127

    24

    newDelegateType (obj.Method)

    A delegate variable stores a method and its receiver, but no parameters !

    new Notifier(myObj.SayHello);

    obj can be this (and can be omitted)

    new Notifier(SayHello)

    Methodcan bestatic. In this case the class name must be specified instead of obj.

    new Notifier(MyClass.StaticSayHello);

    Methodmust not be abstract, but it can be virtual, override, or new.

    Methodsignature must match the signature ofDelegateType

    - same number of parameters

    - same parameter types (including the return type)- same parameter kinds (ref, out, value)

    Multicast Delegates

    A delegate ariable can hold m ltiple al es at the same time

  • 8/12/2019 C# Tutorial - Basics

    90/127

    25

    A delegate variable can hold multiple values at the same time

    Notifier greetings;

    greetings = new Notifier(SayHello);

    greetings += new Notifier(SayGoodBye);

    greetings("John"); // "Hello from John"

    // "Good bye from John"

    greetings -= new Notifier(SayHello);

    greetings("John"); // "Good bye from John"

    Note

    if the multicast delegate is a function, the value of the last call is returned

    if the multicast delegate has an outparameter, the parameter of the last call is returned

    Events = Special Delegate Variables

    class Model {

  • 8/12/2019 C# Tutorial - Basics

    91/127

    26

    class Model {public event Notifier notifyViews;

    public void Change() { ... notifyViews("Model"); }

    }

    class View1 {

    public View1(Model m) { m.notifyViews += new Notifier(this.Update1); }void Update1(string sender) { Console.WriteLine(sender + " was changed"); }

    }

    class View2 {

    public View2(Model m) { m.notifyViews += new Notifier(this.Update2); }

    void Update2(string sender) { Console.WriteLine(sender + " was changed"); }}

    class Test {

    static void Main() {

    Model m = new Model(); new View1(m); new View2(m);

    m.Change();}

    }

    Why events instead of normal delegate variables?

    Only the class that declares the event can fire it (better abstraction).

  • 8/12/2019 C# Tutorial - Basics

    92/127

    27

    Exceptions

    try Statement

    FileStream s = null;

  • 8/12/2019 C# Tutorial - Basics

    93/127

    28

    FileStream s null;try {

    s = new FileStream(curName, FileMode.Open);

    ...

    } catch (FileNotFoundException e) {

    Console.WriteLine("file {0} not found", e.FileName);

    } catch (IOException) {Console.WriteLine("some IO exception occurred");

    } catch {

    Console.WriteLine("some unknown error occurred");

    } finally {

    if (s != null) s.Close();}

    catch clauses are checked in sequential order.

    finally clause is always executed (if present).

    Exception parameter name can be omitted in a catch clause.

    Exception type must be derived from System.Exception.

    If exception parameter is missing, System.Exception is assumed.

    System.Exception

    Properties

  • 8/12/2019 C# Tutorial - Basics

    94/127

    29

    Propertiese.Message the error message as a string;

    set in new Exception(msg);

    e.StackTrace trace of the method call stack as a string

    e.Source the application or object that threw the exceptione.TargetSite the method object that threw the exception

    ...

    Methodse.ToString() returns the name of the exception

    ...

    Throwing an Exception

    By an invalid operation (implicit exception)

  • 8/12/2019 C# Tutorial - Basics

    95/127

    30

    By an invalid operation (implicit exception)

    Division by 0

    Index overflow

    Acess via a null reference

    ...

    By a throw statement (explicit exception)

    throw new FunnyException(10);

    class FunnyException : ApplicationException {public int errorCode;

    public FunnyException(int x) { errorCode = x; }

    }

  • 8/12/2019 C# Tutorial - Basics

    96/127

    Searching for a catch Clause

    F G H

  • 8/12/2019 C# Tutorial - Basics

    97/127

    32

    Caller chain is traversed backwards until a method with a matching catch clause is found.

    If none is found => Program is aborted with a stack trace

    Exceptions don't have to be caught in C# (in contrast to Java)

    No distinction between

    - checked exceptions that have to be caught, and

    - unchecked exceptions that don't have to be caught

    Advantage: convenient

    Disadvantage: less robust software

    ...

    F();

    ...

    try {G();....

    } catch (Exc e) {...

    }

    ...

    H();

    ....

    ...

    throw new FooException(...);

    ....

    No Throws Clause in Method Signature

  • 8/12/2019 C# Tutorial - Basics

    98/127

    33

    Java

    void myMethod() throws IOException {

    ... throw new IOException(); ...

    }

    Callers of myMethodmust either

    - catchIOException or

    - specifyIOExceptions in their own signature

    C#

    void myMethod() {

    ... throw new IOException(); ...

    }

    Callers of myMethodmay handleIOException or not.

    + convenient

    - less robust

  • 8/12/2019 C# Tutorial - Basics

    99/127

    34

    Namespaces and Assemblies

    C# Namespaces vs. Java Packages

    C# Java

  • 8/12/2019 C# Tutorial - Basics

    100/127

    35

    C# Java

    A file may contain multiple namespaces A file may contain just 1 packagexxx.cs xxx.java

    namespace A {...}namespace B {...}

    namespace C {...}

    package A;...

    ...

    Namespaces and classes are not mapped

    to directories and files

    Packages and classes are mapped to

    directories and filesxxx.cs C.java

    namespace A {

    class C {...}

    }

    package A;

    class C {...}

    Samples Samples

    Axxx.cs

    C.java

    Namespaces vs. Packages (continued)

    C# Java

  • 8/12/2019 C# Tutorial - Basics

    101/127

    36

    C# JavaImports namespaces Imports classes

    using System; import java.util.LinkedList;

    import java.awt.*;

    Namespaces are imported in other Namesp. Classes are imported in files

    using A;

    namespace B {

    using C;

    ...

    }

    import java.util.LinkedList;

    Alias names allowed Java has visibilitypackage

    using F = System.Windows.Forms;

    ...

    F.Button b;

    package A;

    class C {

    void f() {...} // package

    }for explicit qualification and short names.

    C# has only visibility internal(!= namespace)

    Assemblies

    Run time unit consisting of types and other resources (e.g. icons)

  • 8/12/2019 C# Tutorial - Basics

    102/127

    37

    - Unit of deployment: assembly is smallest unit that can be deployed individually- Unit of versioning: all types in an assembly have the same version number

    Often: 1 assembly = 1 namespace = 1 program

    But: - one assembly may consist of multiple namespaces.

    - one namespace may be spread over several assemblies.- an assembly may consist of multiple files, held together by a

    manifest("table of contents")

    Assembly JAR file in Java

    Assembly Component in .NET

    namespace AC1 C2

    namespace BC3 C4

    icon assembly

    How are Assemblies Created?

    Every compilation creates either an assembly or a module

  • 8/12/2019 C# Tutorial - Basics

    103/127

    38

    y p y

    sources

    assemblyA.cs

    withmanifest

    executablelibrary

    .exe

    .dllB.cs

    cscmodules

    libraries

    C.netmodule

    D.dll

    module

    withoutmanifest.netmodule

    Only metadata are embedded

    Other modules/resources can be added with the assembly linker (al)

    Difference to Java: Java creates a *.class file for every class

    Compiler Options

    Which output file should be generated?

  • 8/12/2019 C# Tutorial - Basics

    104/127

    39

    /t[arget]: exe output file = console application (default)

    | winexe output file = Windows GUI application

    | library output file = library (DLL)

    | module output file = module (.netmodule)

    /out:name specifies the name of the assembly or module

    default for /t:exe name.exe, where name is the name of the source

    file containing theMain method

    default for /t:library name.dll, where name is the name of the first

    source file

    Example: csc /t:library /out:MyLib.dll A.cs B.cs C.cs

    /doc:name generates an XML file with the specified name from /// comments

    Compiler Options

    How should libraries and modules be embedded?

  • 8/12/2019 C# Tutorial - Basics

    105/127

    40

    /r[eference]:name makes metadata in name (e.g.xxx.dll) available in the compilation.

    name must contain metadata.

    /lib:dirpath{,dirpath} specifies the directories, in which libraries are searched that are

    referenced by /r.

    /addmodule:name {,name} adds the specified modules (e.g.xxx.netmodule) to the generated

    assembly.

    At run time these modules must be in the same directory as the

    assembly to which they belong.

    Example

    csc /r:MyLib.dll /lib:C:\project A.cs B.cs

    Examples for Compilations

    csc A.cs => A.execsc A cs B cs C cs => B exe (if B cs contains Main)

  • 8/12/2019 C# Tutorial - Basics

    106/127

    41

    csc A.cs B.cs C.cs > B.exe (ifB.cs containsMain)

    csc /out:X.exe A.cs B.cs => X.exe

    csc /t:library A.cs => A.dllcsc /t:library A.cs B.cs => A.dll

    csc /t:library /out:X.dll A.cs B.cs => X.dll

    csc /r:X.dll A.cs B.cs => A.exe (whereA orB reference types inX.dll)

    csc /addmodule:Y.netmodule A.cs => A.exe (Yis added to this assembly)

  • 8/12/2019 C# Tutorial - Basics

    107/127

    42

    Attributes

  • 8/12/2019 C# Tutorial - Basics

    108/127

    Attribute with Parameters

    Example[Obsolete("Use class C1 instead" IsError=true)] // causes compiler message saying

    positional

    paramete

    r

    namepa

    rameters

    comeafterpo

    s.param

    eters

  • 8/12/2019 C# Tutorial - Basics

    109/127

    44

    [Obsolete( Use class C1 instead , IsError=true)] // causes compiler message saying

    public class C {...} // that C is obsolete

    Positional parameter = parameter of the attribute's constructor

    Name parameter = a property of the attribute

    Attributes are declared as classes

    public class ObsoleteAttribute : Attribute { // class name ends with "Attribute"public string Message { get; } // but can be used as "Obsolete"

    public bool IsError{ get; set; }public ObsoleteAttribute() {...}public ObsoleteAttribute(string msg) {...}public ObsoleteAttribute(string msg, bool error) {...}

    }

    Valid variants:

    [Obsolete]

    [Obsolete("some Message")]

    [Obsolete("some Message", false)]

    [Obsolete("some Message", IsError=false)]

    value must be a constant

    Example: ConditionalAttribute

    Allows a conditional call of methods

  • 8/12/2019 C# Tutorial - Basics

    110/127

    45

    #define debug // preprocessor command

    class C {

    [Conditional("debug")] // only possible for void methodsstatic void Assert (bool ok, string errorMsg) {

    if (!ok) {Console.WriteString(errorMsg);System.Environment.Exit(0); // graceful program termination

    }}

    static void Main (string[] arg) {Assert(arg.Length > 0, "no arguments specified");Assert(arg[0] == "...", "invalid argument");

    ...}

    }

    Assertis only called, if debugwas defined.

    Also useful for controlling trace output.

    Your Own Attributes

    Declaration[AttributeUsage(AttributeTargets.Class|AttributeTargets.Interface, Inherited=true)]

  • 8/12/2019 C# Tutorial - Basics

    111/127

    46

    [ g ( g | g , )]class Comment : Attribute {

    string text, author;public string Text { get {return text;} }public string Author { get {return author;} set {author = value;} }public Comment (string text) { this.text = text; author ="HM"; }

    }

    Use

    [Comment("This is a demo class for Attributes", Author="XX")]class C { ... }

    Querying the attribute at run time

    class Attributes {

    static void Main() {Type t = typeof(C);object[] a = t.GetCustomAttributes(typeof(Comment), true);Comment ca = (Comment)a[0];Console.WriteLine(ca.Text + ", " + ca.Author);

    }

    }

    search should

    also be continued

    in subclasses

  • 8/12/2019 C# Tutorial - Basics

    112/127

    47

    Threads

    Participating Types (excerpt)

    public sealed class Thread {public static Thread CurrentThread { get; } // static methods

    public static void Sleep(int milliSeconds) {...}

  • 8/12/2019 C# Tutorial - Basics

    113/127

    48

    public static void Sleep(int milliSeconds) {...}

    ...

    public Thread(ThreadStart startMethod) {...} // thread creation

    public string Name { get; set; } // properties

    public ThreadPriority Priority { get; set; }

    public ThreadState ThreadState { get; }

    public bool IsAlive { get; }

    public bool IsBackground { get; set; }

    ...

    public void Start() {...} // methodspublic void Suspend() {...}

    public void Resume() {...}

    public void Join() {...} // caller waits for the thread to die

    public voidAbort() {...} // throws ThreadAbortException

    ...

    }

    public delegate void ThreadStart(); // parameterless void method

    public enum ThreadPriority {AboveNormal, BelowNormal, Highest, Lowest, Normal}

    public enum ThreadState {Aborted, Running, Stopped, Suspended, Unstarted, ...}

    Example

    using System;using System.Threading;

    class Printer {

  • 8/12/2019 C# Tutorial - Basics

    114/127

    49

    class Printer {char ch;int sleepTime;

    public Printer(char c, int t) {ch = c; sleepTime = t;}public void Print() {

    for (int i = 0; i < 100; i++) {Console.Write(ch);Thread.Sleep(sleepTime);

    }

    }}

    class Test {

    static void Main() {Printer a = new Printer('.', 10);Printer b = new Printer('*', 100);new Thread(new ThreadStart(a.Print)).Start();new Thread(new ThreadStart(b.Print)).Start();

    }}

    The program runs until the last thread stops.

    Thread States

    Thread t = new Thread(new ThreadStart(P));Console.WriteLine("name={0}, priority={1}, state={2}", t.Name, t.Priority, t.ThreadState);

    t.Name = "Worker"; t.Priority = ThreadPriority.BelowNormal;

  • 8/12/2019 C# Tutorial - Basics

    115/127

    50

    ; y y ;

    t.Start();

    Thread.Sleep(0);

    Console.WriteLine("name={0}, priority={1}, state={2}", t.Name, t.Priority, t.ThreadState);

    t.Suspend();Console.WriteLine("state={0}", t.ThreadState);

    t.Resume();

    Console.WriteLine("state={0}", t.ThreadState);

    t.Abort();

    Thread.Sleep(0);

    Console.WriteLine("state={0}", t.ThreadState);

    Output

    name=, priority=Normal, state=Unstarted

    name=Worker, priority=BelowNormal, state=Running

    state=Suspendedstate=Running

    state=Stopped

    Example for Join

    using System;

    using System.Threading;

  • 8/12/2019 C# Tutorial - Basics

    116/127

    51

    class Test {

    static void P() {

    for (int i = 1; i

  • 8/12/2019 C# Tutorial - Basics

    117/127

    52

    ( )

    Example

    class Account { // this class should behave like a monitor long val = 0;

    public void Deposit(long x) {lock (this) { val += x; } // only 1 thread at a time may execute this statement

    }

    public void Withdraw(long x) {lock (this) { val -= x; }

    }}

    Lock can be set to any objectobject semaphore = new object();...lock (semaphore) { ... critical region ... }

    No synchronized methods like in Java

    Class Monitor

    lock(v) Statement

    is a shortcut for

  • 8/12/2019 C# Tutorial - Basics

    118/127

    53

    is a shortcut for

    Monitor.Enter(v);

    try {

    Statement

    } finally {

    Monitor.Exit(v);

    }

    Wait and Pulse

    Monitor.Wait(lockedVar);

    wait() in Java (in Java lockedVaris always this)Monitor.Pulse(lockedVar); notify() in JavaMonitor.PulseAll(lockedVar); notifyAll() in Java

  • 8/12/2019 C# Tutorial - Basics

    119/127

    54

    ( ); y ()

    Example

    Thread A Thread B

    lock(v) { lock(v) {

    ... ...

    Monitor.Wait(v); Monitor.Pulse(v);

    ... ...

    } }

    1. A comes to lock(v) and proceeds because the critical region is free.

    2. A comes to Wait, goes to sleep and releases the lock.

    3. B comes to lock(v) and proceeds because the critical region is free.

    4. B comes toPulse and wakes upA. There can be a context switch betweenA andB, but not

    necessarily.

    5. A tries to get the lock but fails, becauseB is still in the critical region.

    6. At the end of the critical regionB releases the lock;A can proceed now.

    1

    2

    3

    45

    6

    Example: Synchronized Buffer

    If producer is fasterPutPut

    class Buffer {const int size = 4;char[] buf = new char[size];int head = 0 tail = 0 n = 0;

  • 8/12/2019 C# Tutorial - Basics

    120/127

    55

    PutPutGet

    PutGet...

    int head = 0, tail = 0, n = 0;

    public void Put(char ch) {lock(this) {

    while (n == size) Monitor.Wait(this);buf[tail] = ch; tail = (tail + 1) % size; n++;Monitor.Pulse(this);

    }}

    public char Get() {lock(this) {

    while (n == 0) Monitor.Wait(this);char ch = buf[head]; head = (head + 1) % size;n--;

    Monitor.Pulse(this);return ch;}

    }}

    If consumer is faster

    PutGetPutGet...

  • 8/12/2019 C# Tutorial - Basics

    121/127

    56

    XML Comments

    Special Comments (like javadoc)

    Example/// ... comment ...

    class C {

  • 8/12/2019 C# Tutorial - Basics

    122/127

    57

    class C {

    /// ... comment ...

    public int f;

    /// ... comment ...

    public void foo() {...}

    }

    Compilation csc /doc:MyFile.xml MyFile.cs

    Checks if comments are complete and consistente.g. if one parameter of a method is documented, all parameters must be documented;

    Names of program elements must be spelled correctly.

    Generates an XML file with the commented program elementsXML can be formatted for the Web browser with XSL

    Example of a Commented Source File

    /// A counter for accumulating values and computing the mean value.class Counter {

    /// The accumulated valuesprivate int value;

  • 8/12/2019 C# Tutorial - Basics

    123/127

    58

    private int value;

    /// The number of added valuespublic int n;

    /// Adds a value to the counter/// The value to be addedpublic void Add(int x) {

    value += x; n++;

    }

    /// Returns the mean value of all accumulated values/// The mean value, i.e. / public float Mean() {

    return (float)value / n;

    }}

    Generated XML File

    MyFile

    XML file can be viewed in

    HTML using Visual Studio.

  • 8/12/2019 C# Tutorial - Basics

    124/127

    59

    name MyFile /name

    A counter for accumulating values and computing the mean value.

    The accumulated values

    The number of added values

    Adds a value to the counter

    The value to be added

    Returns the mean value of all accumulated values

    The mean value, i.e. /

    g

    elements are

    not nested

    hierarchically!

    XML Tags

    Predefined TagsMain tags

    h d i i f l /

  • 8/12/2019 C# Tutorial - Basics

    125/127

    60

    short description of a program element

    extensive description of a program element

    description of a parameter description of the return value

    Tags that are used within other tags

    used in the documentation of a method:

    describes an exception

    sample code

    arbitrary code

    name of a crossreference link

    name of a parameter

    User-defined Tags

    Users may add arbitrary tags, e.g. , , ...

  • 8/12/2019 C# Tutorial - Basics

    126/127

    61

    Summary

    Summary of C#

    Familiar Safe

    Strong static typing

  • 8/12/2019 C# Tutorial - Basics

    127/127

    62

    Strong static typing

    Run time checks

    Garbage Collection

    Versioning

    Expressive Object-oriented (classes, interfaces, ...)

    Component-oriented (properties, events, assemblies, ...)

    Uniform type system (boxing / unboxing) Enumerations

    Delegates

    Indexers

    refand outparameters

    Value objects on the stack Threads and synchronization

    Exceptions

    User attributes

    Reflection

    ...