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

Slides:



Advertisements
Similar presentations
Introduction to Web Application
Advertisements

1 Visual C# "Whidbey": Language Enhancements Anders Hejlsberg Distinguished Engineer Microsoft Corporation Anders Hejlsberg Distinguished.
Generics, Lists, Interfaces
LINQ and Collections An introduction to LINQ and Collections.
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics C# Language &.NET Platform 6 th Lecture Pavel Ježek
C# Language Report By Trevor Adams. Language History Developed by Microsoft Developed by Microsoft Principal Software Architect Principal Software Architect.
Language Fundamentals in brief C# - Introduction.
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics C# Language &.NET Platform 2 nd Lecture Pavel Ježek
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics C# Language &.NET Platform 4 th Lecture Pavel Ježek
CS 4800 By Brandon Andrews.  Specifications  Goals  Applications  Design Steps  Testing.
Collections. 2 Objectives Explore collections in System.Collections namespace –memory management –containment testing –sorting –traversal.
C#.NET C# language. C# A modern, general-purpose object-oriented language Part of the.NET family of languages ECMA standard Based on C and C++
Iterator Pattern Dr. Neal CIS 480. Iterator An iterator pattern can be used when one class is a collection of things and would like to provide a standardized.
5. OOP. 2 Microsoft Objectives “Classes, objects and object-oriented programming (OOP) play a fundamental role in.NET. C# features full support for the.
Differences between C# and C++ Dr. Catherine Stringfellow Dr. Stewart Carpenter.
Classes, Objects, Arrays, Collections and Autoboxing Dr. Andrew Wallace PhD BEng(hons) EurIng
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics C# Language &.NET Platform 7 th & 8 th Lecture Pavel Ježek.
Equality Programming in C# Equality CSE / ECE 668 Prof. Roger Crawfis.
Advanced .NET Programming I 13th Lecture
BIM313 – Advanced Programming Techniques Object-Oriented Programming 1.
Common Type System .NET Types Hierarchy, Cloning, Comparing, Collection Iterators, Value and Reference Types SoftUni Team Technical Trainers Software.
Copyright © 2006 Thomas P. Skinner1 Chapter 5 Indexers, Interfaces, and Enumerators.
FEN 2012 UCN Technology: Computer Science1 C# - Introduction Language Fundamentals in Brief.
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics C# Language &.NET Platform 11 th Lecture Pavel Ježek
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Session 08 Module 14: Generics and Iterator Module 15: Anonymous & partial class & Nullable type.
Modern Software Development Using C#.NET Chapter 5: More Advanced Class Construction.
Hoang Anh Viet Hà Nội University of Technology Chapter 1. Introduction to C# Programming.
Neal Stublen What’s an indexer?  An array has an indexer… int[] myArray = new int[5]; for (int index = 0; index < 5; ++index) {
Advanced C# Types Tom Roeder CS fa. From last time out parameters difference is that the callee is required to assign it before returning not the.
Bill Campbell, UMB Microsoft's.NET C# and The Common Language Runtime.
Common Type System.NET Types Hierarchy, Cloning, Comparing, Collection Iterators, Value and Reference Types Svetlin Nakov Technical Trainer
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics Advanced.NET Programming I 10 th Lecture Pavel Ježek
Inside LINQ to Objects How LINQ to Objects work Inside LINQ1.
Neal Stublen Tonight’s Agenda  Indexers  Delegates and events  Operator overloading  Class inheritance  Q&A.
Advanced C#, part I Niels Hallenberg IT University of Copenhagen BAAAP – Spring 2009.
PROGRAMMING IN C#. Collection Classes (C# Programming Guide) The.NET Framework provides specialized classes for data storage and retrieval. These classes.
Microsoft.NET Вторая лекция. Reference and value types public class RefType { } public struct ValueType : IDisposable { public int A, B; public ValueType(int.
Generics Generics vs. heterogeneous collections Doing your own generics FEN 2014UCN Teknologi/act2learn1.
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics C# Language &.NET Platform 6 th Lecture Pavel Ježek
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics C# Language &.NET Platform 8 th Lecture Pavel Ježek
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics C# Language &.NET Platform 11 th Lecture Pavel Ježek
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics C# Language &.NET Platform 9 th Lecture Pavel Ježek
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics C# Language &.NET Platform 2 nd Lecture Pavel Ježek
Changing Comparison Programming in C# Changing Comparison CSE 494R (proposed course for 459 Programming in C#) Prof. Roger Crawfis.
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics C# Language &.NET Platform 4 th Lecture Pavel Ježek
- This slide is intentionally left blank - Some of the slides are based on University of Linz.NET presentations. © University of Linz, Institute for System.
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics C# Language &.NET Platform 7 th Lecture Pavel Ježek
C# Fundamentals An Introduction. Before we begin How to get started writing C# – Quick tour of the dev. Environment – The current C# version is 5.0 –
Chapter  Array-like data structures  ArrayList  Queue  Stack  Hashtable  SortedList  Offer programming convenience for specific access.
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics Advanced.NET Programming II 5 th Lecture Pavel Ježek
1 New Features in C# 2.0 Generic Types Iterators Simplified Delegates Anonymous Methods Partial Types Various © University of Linz, Institute for System.
Lecture 8: Collections, Comparisons and Conversions. Svetla Boytcheva AUBG, Spring COS 240 Object-Oriented Languages.
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics Advanced.NET Programming II 3 rd Lecture Pavel Ježek
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics Advanced.NET Programming II 2 nd Lecture Pavel Ježek
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics Advanced.NET Programming I 2 nd Lecture Pavel Ježek
Advanced .NET Programming I 2nd Lecture
Advanced .NET Programming I 3nd Lecture
5.1 Being Objects and A Glimpse into Coding
null, true, and false are also reserved.
Conditional Statements
Module 2 Variables, Assignment, and Data Types
C# Language & .NET Platform 10th Lecture
- This slide is intentionally left blank -
Advanced .NET Programming I 3rd Lecture
C# Language & .NET Platform 11th Lecture
Advanced .NET Programming I 6th Lecture
C# Language & .NET Platform 9th Lecture
C# Language & .NET Platform 12th Lecture
5. OOP OOP © 2003 Microsoft.
Presentation transcript:

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 (

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

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

Interfaces

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

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

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

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

Interfaces and Value Types

Covariance and Contravariance

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

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

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

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.

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

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 }

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

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

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

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

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

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

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

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

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

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!

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

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

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

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

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