charles university in prague jezek faculty of mathematics and physics c# language &.net platform...

31
CHARLES UNIVERSITY IN PRAGUE http://d3s.mff.cuni.cz/~jezek faculty of mathematics and physics C# Language & .NET Platform 12 th -13 th Lecture Pavel Ježek [email protected]ff.cun i.cz Some of the slides are based on University of Linz .NET presen © University of Linz, Institute for System Software, 20 published under the Microsoft Curriculum License (http://www.msdnaa.net/curriculum/license_curriculum.asp

Upload: jeffrey-cluett

Post on 14-Dec-2015

219 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: CHARLES UNIVERSITY IN PRAGUE jezek faculty of mathematics and physics C# Language &.NET Platform 12 th -13 th Lecture Pavel Ježek

CHARLES UNIVERSITY IN PRAGUE

http://d3s.mff.cuni.cz/~jezek

faculty of mathematics and physics

C# Language & .NET Platform

12th-13th Lecture

Pavel Jež[email protected]

Some of the slides are based on University of Linz .NET presentations.© University of Linz, Institute for System Software, 2004

published under the Microsoft Curriculum License(http://www.msdnaa.net/curriculum/license_curriculum.aspx)

Page 2: CHARLES UNIVERSITY IN PRAGUE jezek faculty of mathematics and physics C# Language &.NET Platform 12 th -13 th Lecture Pavel Ježek

CLI Type SystemAll types

Reference types(allocated on

managed heap)

PointersValue types(allocated in-place

[with exceptions])

Classes(e.g. strings)

Interfaces Arrays Delegates

Simple types(Int32, Int64,

Double, Boolean, Char, …)

Nullables

EnumerationsStructures

User defined structures

Page 3: CHARLES UNIVERSITY IN PRAGUE jezek faculty of mathematics and physics C# Language &.NET Platform 12 th -13 th Lecture Pavel Ježek

CLI Type InheritanceSystem.Object(C# keyword: object)

user-defined classes(C# keyword: class)

delegates(C# keyword: delegate)

pointers(C#: Type *)

System.Delegate

System.MulticastDelegate

System.ValueType

System.Enum

System.Array

arrays(C#: Type[] or Type[,])

System.String(C# keyword: string)

interfaces(C# keyword: interface)

user-defined structures

(C# keyword: struct)

enumerations(C# keyword: enum)

System.Int32(C# keyword: int)

System.Int64(C# keyword: long)

System.Double(C# keyword: double)

System.Boolean(C# keyword: bool)

simple types

System.Nullable(C#: Type?)

Page 4: CHARLES UNIVERSITY IN PRAGUE jezek faculty of mathematics and physics C# Language &.NET Platform 12 th -13 th Lecture Pavel Ježek

Interfaces

Page 5: CHARLES UNIVERSITY IN PRAGUE jezek faculty of mathematics and physics C# Language &.NET Platform 12 th -13 th Lecture Pavel Ježek

Interface Constraints: Is It Correct?interface I1 {

void m();} interface I2 {

void m();} class B : I1, I2 {

public void m() {Console.WriteLine("B.m()");

}} class Y<T> where T : I1, I2 {

public static void m(T t) {t.m();

}} class Program {

static void Main(string[] args) {new B().m();Y<B>.m(new B());

}}

Page 6: CHARLES UNIVERSITY IN PRAGUE jezek faculty of mathematics and physics C# Language &.NET Platform 12 th -13 th Lecture Pavel Ježek

Implementing Generic Interfaces

interface I<T> {

void m(T x);

T m();

}

 

class A : I<int>, I<long> {

?}

Page 7: CHARLES UNIVERSITY IN PRAGUE jezek faculty of mathematics and physics C# Language &.NET Platform 12 th -13 th Lecture Pavel Ježek

Implementing Generic Interfaces

interface I<T> {

void m(T x);

T m();

}

 

class A : I<int>, I<long> {

public void m(int x) { Console.WriteLine("int m"); }

public void m(long x) { Console.WriteLine("long m"); }

public int m() { return -1; }

long I<long>.m() { return -2; }

}

class Program {

static void Main(string[] args) {

A a = new A();

a.m(0);

a.m(0L); // Same as a.m(0l);

((I<int>) a).m(0);

((I<long>) a).m(0);

Console.WriteLine(a.m());

Console.WriteLine(((I<long>) a).m());

}

}

Page 8: CHARLES UNIVERSITY IN PRAGUE jezek faculty of mathematics and physics C# Language &.NET Platform 12 th -13 th Lecture Pavel Ježek

Implementing Generic Interfaces

interface I<T> {

void m(T x);

T m();

}

 

class A : I<int>, I<long> {

public void m(int x) { Console.WriteLine("int m"); }

public void m(long x) { Console.WriteLine("long m"); }

public int m() { return -1; }

long I<long>.m() { return -2; }

}

class Program {

static void Main(string[] args) {

A a = new A();

a.m(0);

a.m(0L); // Same as a.m(0l);

((I<int>) a).m(0);

((I<long>) a).m(0);

Console.WriteLine(a.m());

Console.WriteLine(((I<long>) a).m());

}

}

Page 9: CHARLES UNIVERSITY IN PRAGUE jezek faculty of mathematics and physics C# Language &.NET Platform 12 th -13 th Lecture Pavel Ježek

Interfaces and Value Types

Page 10: CHARLES UNIVERSITY IN PRAGUE jezek faculty of mathematics and physics C# Language &.NET Platform 12 th -13 th Lecture Pavel Ježek

Covariance and Contravariance

Page 11: CHARLES UNIVERSITY IN PRAGUE jezek faculty of mathematics and physics C# Language &.NET Platform 12 th -13 th Lecture Pavel Ježek

Any Meaningful Application of the Type Below?

struct X<T> where T : class {

private T t;

public static implicit operator T(X<T> x) {

return x.t; 

}

public static implicit operator X<T>(T t) {

X<T> x;

x.t = t;

return x;

}

}

Page 12: CHARLES UNIVERSITY IN PRAGUE jezek faculty of mathematics and physics C# Language &.NET Platform 12 th -13 th Lecture Pavel Ježek

IDisposable

public interface IDisposable {void Dispose()

}

public class ObjectDisposedException : InvalidOperationException {}

Page 13: CHARLES UNIVERSITY IN PRAGUE jezek faculty of mathematics and physics C# Language &.NET Platform 12 th -13 th Lecture Pavel Ježek

Class System.Object

Topmost base class of all other classesclass Object {

protected object MemberwiseClone() {...}public Type GetType() {...}public virtual bool Equals (object o) {...}public virtual string ToString() {...}public virtual int GetHashCode() {...}public static bool ReferenceEquals(object objA, object objB);

}

Page 14: CHARLES UNIVERSITY IN PRAGUE jezek faculty of mathematics and physics C# Language &.NET Platform 12 th -13 th Lecture Pavel Ježek

IEqualityComparer<in T>

EqualityComparer<T>.Default: a default implementation of a IEqualityComparer<T> for type T

public interface IEqualityComparer<in T> {int GetHashCode(T obj);bool Equals(T x, T y);

}

Used by Dictionary<T> and HashSet<T> collections.

Page 15: CHARLES UNIVERSITY IN PRAGUE jezek faculty of mathematics and physics C# Language &.NET Platform 12 th -13 th Lecture Pavel Ježek

Class System.Object

Topmost base class of all other classesclass Object {

protected object MemberwiseClone() {...}public Type GetType() {...}public virtual bool Equals (object o) {...}public virtual string ToString() {...}public virtual int GetHashCode() {...}public static bool ReferenceEquals(object objA, object objB);

}

Page 16: CHARLES UNIVERSITY IN PRAGUE jezek faculty of mathematics and physics C# Language &.NET Platform 12 th -13 th Lecture Pavel Ježek

Sorting: IComparable and IComparer

IComparable is interface for types with order

classes implementing IComparable arevalues types like Int32, Double, DateTime, …class Enum as base class of all enumeration typesclass String

IComparer is interface for the realization of compare operators

public interface IComparer {int Compare(object x, object y); // <0 if x < y, 0 if x == y, >0 if x > y

}

public interface IComparer<in T> {int Compare(T x, T y); // <0 if x < y, 0 if x == y, >0 if x > y

}

public interface IComparable {int CompareTo(object obj); // <0 if this < obj, 0 if this == obj, >0 if this > obj

}

public interface IComparable<in T> {int CompareTo(T obj); // <0 if this < obj, 0 if this == obj, >0 if this > obj

}

Page 17: CHARLES UNIVERSITY IN PRAGUE jezek faculty of mathematics and physics C# Language &.NET Platform 12 th -13 th Lecture Pavel Ježek

Custom IComparer Implementation

Creation of table of strings:

string[][] Table = {new string[] {"John", "Dow", "programmer"},new string[] {"Bob", "Smith", "agent"},new string[] {"Jane", "Dow", "assistant"},new string[] {"Jack", "Sparrow", "manager"}

};

Printing the table:

foreach (string[] Row in Table) {Console.WriteLine(String.Join(", ", Row));

}

Page 18: CHARLES UNIVERSITY IN PRAGUE jezek faculty of mathematics and physics C# Language &.NET Platform 12 th -13 th Lecture Pavel Ježek

Custom IComparer Implementation (2)

Comparer for single table (array) column:

class ArrayComparer<T> : IComparer<T[]> where T : IComparable<T> {private int m_Index;

public ArrayComparer(int Index) {m_Index = Index;

}

public int Compare(T[] x, T[] y) {return x[m_Index].CompareTo(y[m_Index]);

}}

Printing the table:

Array.Sort(Employees, new ArrayComparer<string>(2));

foreach (string[] Row in Employees) {Console.WriteLine(String.Join(", ", Row));

}

Bob, Smith, agentJane, Dow, assistantJack, Sparrow, managerJohn, Dow, programmer

Page 19: CHARLES UNIVERSITY IN PRAGUE jezek faculty of mathematics and physics C# Language &.NET Platform 12 th -13 th Lecture Pavel Ježek

"BCL v2-friendly" Custom Classes 1/3

In order to cooperate smoothly with other BCL classesin the framework 2.0, custom classes should:

override ToString and GetHashCode

overload == and !=

implement ICloneable public interface ICloneable { object Clone(); }

class MyClass : ICloneable { public object Clone() { return MemberwiseClone(); } }

Page 20: CHARLES UNIVERSITY IN PRAGUE jezek faculty of mathematics and physics C# Language &.NET Platform 12 th -13 th Lecture Pavel Ježek

"BCL v2-friendly" Custom Classes 2/3

implement IComparable and IComparable<T> public interface IComparable { int CompareTo(object obj); // <0: this < obj, 0: this == obj, >0: this > obj }

public interface IComparable<T> { int CompareTo(T obj); // <0: this < obj, 0: this == obj, >0: this > obj }

class Fraction : IComparable, IComparable<Fraction> { int n, d;

public int CompareTo(object obj) { if (f == null) return 1; if (!(obj is Fraction)) throw new ArgumentException(“Must be of Fraction type.”, “obj”); return CompareTo((Fraction) obj); }

public int CompareTo(Fraction f) { if (f == null) return 1;

return n*f.d – f.n*d } }

Page 21: CHARLES UNIVERSITY IN PRAGUE jezek faculty of mathematics and physics C# Language &.NET Platform 12 th -13 th Lecture Pavel Ježek

"BCL v2-friendly" Custom Classes 3/3

override Equals(object) and implement IEquatable<T> public class Object { public virtual bool Equals(Object obj); … }

public interface IEquatable<T> { bool Equals(T other); }

class Fraction : IEquatable<Fraction> { // equal to class Fraction : object, IEquatable<Fraction> int n, d; public override bool Equals(object obj) { Fraction f = obj as Fraction; if (f == null) return false; return Equals(f); }

public bool Equals(Fraction f) { return f.n == n && f.d == d; } }

Page 22: CHARLES UNIVERSITY IN PRAGUE jezek faculty of mathematics and physics C# Language &.NET Platform 12 th -13 th Lecture Pavel Ježek

interface IEnumerator {object Current {get;}bool MoveNext();void Reset();

}

IEnumerable and IEnumerator (1)

Anything which is enumerable is represented by interface IEnumerable

IEnumerator realizes an iterator

Also generic versions IEnumerable<out T> and IEnumerator<out T>Enumerator should throw an InvalidOperationException on concurrent modification!

interface IEnumerable { IEnumerator GetEnumerator(); }

Page 23: CHARLES UNIVERSITY IN PRAGUE jezek faculty of mathematics and physics C# Language &.NET Platform 12 th -13 th Lecture Pavel Ježek

IEnumerable and IEnumerator

following statement:

foreach (ElementType element in collection) statement;

is translated into:

IEnumerator enumerator = ((IEnumerable) collection).GetEnumerator();try {

ElementType element;while (enumerator.MoveNext()) {

element = (ElementType) enumerator.Current;statement;

}} finally {

IDisposable disposable = enumerator as IDisposable;if (disposable != null) disposable.Dispose();

}

Page 24: CHARLES UNIVERSITY IN PRAGUE jezek faculty of mathematics and physics C# Language &.NET Platform 12 th -13 th Lecture Pavel Ježek

IEnumerable and IEnumerator (optimized)

following statement:

foreach (ElementType element in collection) statement;

is translated into:

var enumerator = collection.GetEnumerator();try {

ElementType element;while (enumerator.MoveNext()) {

element = (ElementType) enumerator.Current;statement;

}} finally {

IDisposable disposable = enumerator as IDisposable;if (disposable != null) disposable.Dispose();

}

Page 25: CHARLES UNIVERSITY IN PRAGUE jezek faculty of mathematics and physics C# Language &.NET Platform 12 th -13 th Lecture Pavel Ježek

Iterators so far

foreach loop can be applied to objects of classes which implement IEnumerable

class MyClass: IEnumerable<T> { ... public IEnumerator<T> GetEnumerator() { return new MyEnumerator(...); }

private class MyEnumerator: IEnumerator<string> { public string Current { get {...} } public bool MoveNext() {...} public void Reset() {...} }}

MyClass x = new MyClass();...foreach (string s in x) ...

complicated to implement!!

interface IEnumerable<T> { IEnumerator<T> GetEnumerator();}

Page 26: CHARLES UNIVERSITY IN PRAGUE jezek faculty of mathematics and physics C# Language &.NET Platform 12 th -13 th Lecture Pavel Ježek

Iterator Methods

class MyClass { string first = "first"; string second = "second"; string third = "third"; ... public IEnumerator<string> GetEnumerator() { yield return first; yield return second; yield return third; }}

Characteristics of an interator method

1. has the signaturepublic IEnumerator<T> GetEnumerator

2. statement body contains at leastone yield statement

MyClass x = new MyClass();...foreach (string s in x) Console.Write(s + " ");// prints "first second third "

1. returns a sequence of values

2. foreach loop traverses this sequence

How does an iterator method work?

Note• MyClass need not implement IEnumerable!

Page 27: CHARLES UNIVERSITY IN PRAGUE jezek faculty of mathematics and physics C# Language &.NET Platform 12 th -13 th Lecture Pavel Ježek

What Happens Behind the Scene?

public IEnumerator<int> GetEnumerator() { try { ... } finally { ... }}

returns an object of the following class

class _Enumerator1 : IEnumerator<int> { int Current { get {...} } bool MoveNext() {...} void Dispose() {...}}

foreach (int x in list) Console.WriteLine(x);

is translated into

IEnumerator<int> _e = list.GetEnumerator();try { while (_e.MoveNext()) Console.WriteLine(_e.Current);} finally { if (_e != null) _e.Dispose();}

MoveNext runs to the next yield statement

Dispose executes a possibly existingfinally block in the iterator method

Page 28: CHARLES UNIVERSITY IN PRAGUE jezek faculty of mathematics and physics C# Language &.NET Platform 12 th -13 th Lecture Pavel Ježek

Implementationclass Stack<T>: IEnumerable<T> {

... public IEnumerator<T> GetEnumerator() {

return new __Enumerator1(this);}

class __Enumerator1: IEnumerator<T>, IEnumerator { int __state; T __current; Stack<T> __this; int i;

... public bool MoveNext() {

switch (__state) { case 1: goto __state1; case 2: goto __state2; } i = __this.count - 1; __loop: if (i < 0) goto __state2; __current = __this.items[i]; __state = 1; return true; __state1: --i; goto __loop; __state2: __state = 2; return false; }}

}

class Stack<T>: IEnumerable<T> {T[] items;int count;

public void Push(T item) { } public T Pop() { }

public IEnumerator<T> GetEnumerator() { for (int i = count - 1; i >= 0; --i) {

yield return items[i]; }

}}

Page 29: CHARLES UNIVERSITY IN PRAGUE jezek faculty of mathematics and physics C# Language &.NET Platform 12 th -13 th Lecture Pavel Ježek

yield Statement

2 kinds

yield return expr; • yields a value for the foreach loop• may only occur in an iterator method• type of expr must be compatible with

- T (if IEnumerator<T>)- object (otherwise)

yield break; • terminates the iteration• may only occur in an iterator method

Page 30: CHARLES UNIVERSITY IN PRAGUE jezek faculty of mathematics and physics C# Language &.NET Platform 12 th -13 th Lecture Pavel Ježek

Specific Iterators

class MyList { int[] data = ...;

public IEnumerator<int> GetEnumerator() { for (int i = 0; i < data.Length; i++) yield return data[i]; }

}

Standard iterator

Specific iterator as a method• arbitrary name and parameter list• result type IEnumerable or IEnumerable<T>

public IEnumerable<int> Range(int from, int to) { if (to > data.Length) to = data.Length; for (int i = from; i < to; i++) yield return data[i];}

Specific iterator as a property• arbitrary name• result type IEnumerable or IEnumerable<T>

public IEnumerable<int> Downwards { get { for (int i = data.Length - 1; i >= 0; i--) yield return data[i]; }}

MyList list = new MyList();foreach (int x in list) Console.WriteLine(x);foreach (int x in list.Range(2, 7)) Console.WriteLine(x);foreach (int x in list.Downwards) Console.WriteLine(x);

Page 31: CHARLES UNIVERSITY IN PRAGUE jezek faculty of mathematics and physics C# Language &.NET Platform 12 th -13 th Lecture Pavel Ježek

How Specific Iterators are Compiled

public IEnumerable<int> Range(int from, int to) { if (to > data.Length) to = data.Length; for (int i = from; i < to; i++) yield return data[i];}

class _Enumerable : IEnumerable<int> { IEnumerator<int> GetEnumerator();}

class _Enumerator : IEnumerator<int> { int from, to; int Current { get {...} } bool MoveNext() {...} void Dispose() {..}}

returns an object of the following class

this returns an object of the following class

foreach (int x in list.Range(2, 7)) Console.WriteLine(x);

IEnumerator<int> _e = list.Range(2, 7).GetEnumerator();try { while (_e.MoveNext()) Console.WriteLine(_e.Current);} finally { if (_e != null) _e.Dispose();}

is translated into