csharp4 generics

23
Abed El-Azeem Bukhari (MCPD,MCTS and MCP) el-bukhari.com

Upload: abed-elazeem-bukhari

Post on 10-May-2015

1.325 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Csharp4 generics

Abed El-Azeem Bukhari (MCPD,MCTS and MCP)el-bukhari.com

Page 2: Csharp4 generics

Generics

Prepared By : Abed ElAzeem Bukhari

What’s in This Chapter?

➤An overview of generics ➤ Creating generic classes ➤ Features of generic classes ➤ Generic interfaces ➤ Generic structs ➤ Generic methods

Page 3: Csharp4 generics

Generics OverviewThe following sections explore the advantages and

disadvantages of generics, particularly in regard to:

➤ Performance ➤ Type safety ➤ Binary code reuse ➤ Code bloat ➤ Naming guidelines

Page 4: Csharp4 generics

Performancevar list = new ArrayList();list.Add(44); // boxing — convert a value type to a reference typeint i1 = (int)list[0]; // unboxing — convert a reference type to// a value typeforeach (int i2 in list){Console.WriteLine(i2); // unboxing}

var list = new List < int > ();list.Add(44); // no boxing — value types are stored in the List < int >int i1 = list[0]; // no unboxing, no cast neededforeach (int i2 in list){Console.WriteLine(i2);}

Page 5: Csharp4 generics

Type safetyvar list = new ArrayList();list.Add(44);list.Add("mystring");list.Add(new MyClass());

foreach (int i in list){Console.WriteLine(i);}

var list = new List<int>();list.Add(44);list.Add("mystring"); // compile time errorlist.Add(new MyClass()); // compile time error

Page 6: Csharp4 generics

binary Code reusevar list = new List<int>();list.Add(44);

var stringList = new List<string>();stringList.Add("mystring");

var myClassList = new List<MyClass>();myClassList.Add(new MyClass());

Page 7: Csharp4 generics

Code bloatwhen the generic classes are compiled by the JITcompiler to native code, a new class for every specific value type is created. Reference types share all thesame implementation of the same native class.

This is because with reference types, only a 4-byte memoryaddress (with 32-bit systems) is needed within the generic instantiated class to reference a reference type.

Page 8: Csharp4 generics

naming guidelines

Generic type names should be prefixed with the letter T.

Page 9: Csharp4 generics

Creating Generic Classes

LinkedListObjects/LinkedListNode.csLinkedListObjects/LinkedList.csLinkedListObjects/Program.cs

LinkedListSample/LinkedListNode.csLinkedListSample/LinkedList.csLinkedListSample/Program.cs

Page 10: Csharp4 generics

Generics FeaTures

➤ Default values ➤ Constraints ➤ Inheritance ➤ Static members

DocumentManager/DocumentManager.cs

Page 11: Csharp4 generics

default Valuespublic T GetDocument(){T doc = default(T);lock (this){doc = documentQueue.Dequeue();}return doc;}

Page 12: Csharp4 generics

ConstraintsDocumentManager/Document.csDocumentManager/DocumentManager.csDocumentManager/Program.cs

Page 13: Csharp4 generics

inheritancepublic class LinkedList<T>: IEnumerable<T>{//...A generic type can implement a generic interface. The same is possible by deriving from a class. A generic class can be derived from a generic base class:public class Base<T>{}public class Derived<T>: Base<T>{}The requirement is that the generic types of the interface must be repeated, or the type of the base class mustbe specified, as in this case:public class Base<T>{}public class Derived<T>: Base<string>{}

Page 14: Csharp4 generics

Inheritance cont.public abstract class Calc<T>{public abstract T Add(T x, T y);public abstract T Sub(T x, T y);}public class IntCalc: Calc<int>{public override int Add(int x, int y){return x + y;}public override int Sub(int x, int y){return x — y;}}

Page 15: Csharp4 generics

static memberspublic class StaticDemo<T>{public static int x;}

StaticDemo<string>.x = 4;StaticDemo<int>.x = 5;Console.WriteLine(StaticDemo<string>.x); // writes 4

Page 16: Csharp4 generics

Generic interfacespublic interface IComparable<in T>{int CompareTo(T other);}The older, non-generic IComparable interface requires an object with the CompareTo() method. Thisrequires a cast to specific types, such as to the Person class for using the LastName property:public class Person: IComparable{public int CompareTo(object obj){Person other = obj as Person;return this.lastname.CompareTo(other.LastName);}//When implementing the generic version, it is no longer necessary to cast the object to a Person:public class Person: IComparable<Person>{public int CompareTo(Person other){return this.LastName.CompareTo(other.LastName);}//...

Page 17: Csharp4 generics

Covariance and Contra-varianceVariance/Shape.csVariance/Rectangle.cs

Page 18: Csharp4 generics

Covariance with generic interfaces

Variance/IIndex.csVariance/RectangleCollection.csVariance/Program.cs

Page 19: Csharp4 generics

Contra-Variance with generic interfaces

Variance/IDisplay.csVariance/ShapeDisplay.csVariance/Program.cs

Page 20: Csharp4 generics

generic methodsThe method Swap<T>() defines T as a generic type that is used for two arguments and a variable temp:void Swap<T>(ref T x, ref T y){T temp;temp = x;x = y;y = temp;}A generic method can be invoked by assigning the generic type with the method call:int i = 4;int j = 5;Swap<int>(ref i, ref j);However, because the C# compiler can get the type of the parameters by calling the Swap() method, it isnot required to assign the generic type with the method call. The generic method can be invoked as simplyas non-generic methods:int i = 4;int j = 5;Swap(ref i, ref j);

Page 21: Csharp4 generics

generic methods exampleGenericMethods/Account.csGenericMethods/Program.csGenericMethods/Algorithm.cs

Page 22: Csharp4 generics

generic methods with ConstraintsGenericMethods/Algorithm.csGenericMethods/Account.csGenericMethods/IAccount.csGenericMethods/Program.cs

Page 23: Csharp4 generics

Thanks For Attending

Abed El-Azeem Bukhari (MCPD,MCTS and MCP)

el-bukhari.com