Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics C# Language &.NET Platform 12 th -13 th Lecture Pavel Ježek."— Presentation transcript:

1 CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics C# Language &.NET Platform 12 th -13 th Lecture Pavel Ježek 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)

2 CLI Type System All types Reference types (allocated on managed heap) PointersValue types (allocated in-place [with exceptions] ) Classes (e.g. strings) Interfaces ArraysDelegates Simple types (Int32, Int64, Double, Boolean, Char, …) Nullables Enumerations Structures User defined structures

3 CLI Type Inheritance System.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? )

4 Interfaces

5 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 where T : I1, I2 { public static void m(T t) { t.m(); } class Program { static void Main(string[] args) { new B().m(); Y.m(new B()); }

6 Implementing Generic Interfaces interface I { void m(T x); T m(); } class A : I, I { ? }

7 Implementing Generic Interfaces interface I { void m(T x); T m(); } class A : I, I { 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.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 ) a).m(0); Console.WriteLine(a.m()); Console.WriteLine(((I ) a).m()); }

8 Implementing Generic Interfaces interface I { void m(T x); T m(); } class A : I, I { 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.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 ) a).m(0); Console.WriteLine(a.m()); Console.WriteLine(((I ) a).m()); }

9 Interfaces and Value Types

10 Covariance and Contravariance

11 Any Meaningful Application of the Type Below? struct X where T : class { private T t; public static implicit operator T(X x) { return x.t; } public static implicit operator X (T t) { X x; x.t = t; return x; }

12 IDisposable public interface IDisposable { void Dispose() } public class ObjectDisposedException : InvalidOperationException {}

13 Class System.Object Topmost base class of all other classes class 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); }

14 IEqualityComparer IEqualityComparer EqualityComparer.Default: a default implementation of a IEqualityComparer for type T public interface IEqualityComparer { int GetHashCode(T obj); bool Equals(T x, T y); } Used by Dictionary and HashSet collections.

15 Class System.Object Topmost base class of all other classes class 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); }

16 Sorting: IComparable and IComparer IComparable is interface for types with order classes implementing IComparable are values types like Int32, Double, DateTime, … class Enum as base class of all enumeration types class String IComparer is interface for the realization of compare operators public interface IComparer { int Compare(object x, object y); // 0 if x > y } public interface IComparer { int Compare(T x, T y); // 0 if x > y } public interface IComparable { int CompareTo(object obj); // 0 if this > obj } public interface IComparable { int CompareTo(T obj); // 0 if this > obj }

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

18 Custom IComparer Implementation (2) Comparer for single table (array) column: class ArrayComparer : IComparer where T : IComparable { 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 (2)); foreach (string[] Row in Employees) { Console.WriteLine(String.Join(", ", Row)); } Bob, Smith, agent Jane, Dow, assistant Jack, Sparrow, manager John, Dow, programmer

19 "BCL v2-friendly" Custom Classes 1/3 In order to cooperate smoothly with other BCL classes in 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(); } }

20 "BCL v2-friendly" Custom Classes 2/3 implement IComparable and IComparable public interface IComparable { int CompareTo(object obj); // 0: this > obj } public interface IComparable { int CompareTo(T obj); // 0: this > obj } class Fraction : IComparable, IComparable { 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 }

21 "BCL v2-friendly" Custom Classes 3/3 override Equals(object) and implement IEquatable public class Object { public virtual bool Equals(Object obj); … } public interface IEquatable { bool Equals(T other); } class Fraction : IEquatable { // equal to class Fraction : object, IEquatable 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; }

22 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 and IEnumerator Enumerator should throw an InvalidOperationException on concurrent modification! interface IEnumerable { IEnumerator GetEnumerator(); }

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

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

25 Iterators so far foreach loop can be applied to objects of classes which implement IEnumerable class MyClass: IEnumerable {... public IEnumerator GetEnumerator() { return new MyEnumerator(...); } private class MyEnumerator: IEnumerator { public string Current { get {...} } public bool MoveNext() {...} public void Reset() {...} } MyClass x = new MyClass();... foreach (string s in x)... complicated to implement!! interface IEnumerable { IEnumerator GetEnumerator(); }

26 Iterator Methods class MyClass { string first = "first"; string second = "second"; string third = "third";... public IEnumerator GetEnumerator() { yield return first; yield return second; yield return third; } Characteristics of an interator method 1.has the signature public IEnumerator GetEnumerator 2.statement body contains at least one 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!

27 What Happens Behind the Scene? public IEnumerator GetEnumerator() { try {... } finally {... } returns an object of the following class class _Enumerator1 : IEnumerator { int Current { get {...} } bool MoveNext() {...} void Dispose() {...} } foreach (int x in list) Console.WriteLine(x); is translated into IEnumerator _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 existing finally block in the iterator method

28 Implementation class Stack : IEnumerable {... public IEnumerator GetEnumerator() { return new __Enumerator1(this); } class __Enumerator1: IEnumerator, IEnumerator { int __state; T __current; Stack __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 : IEnumerable { T[] items; int count; public void Push(T item) { } public T Pop() { } public IEnumerator GetEnumerator() { for (int i = count - 1; i >= 0; --i) { yield return items[i]; } } }

29 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 ) - object (otherwise) yield break; terminates the iteration may only occur in an iterator method

30 Specific Iterators class MyList { int[] data =...; public IEnumerator 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 public IEnumerable 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 public IEnumerable 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);

31 How Specific Iterators are Compiled public IEnumerable 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 { IEnumerator GetEnumerator(); } class _Enumerator : IEnumerator { 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 _e = list.Range(2, 7).GetEnumerator(); try { while (_e.MoveNext()) Console.WriteLine(_e.Current); } finally { if (_e != null) _e.Dispose(); } is translated into


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

Similar presentations


Ads by Google