csharp4 generics

Post on 10-May-2015

1.327 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

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

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

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

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

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

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

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.

naming guidelines

Generic type names should be prefixed with the letter T.

Creating Generic Classes

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

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

Generics FeaTures

➤ Default values ➤ Constraints ➤ Inheritance ➤ Static members

DocumentManager/DocumentManager.cs

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

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

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

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

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

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

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

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

Covariance with generic interfaces

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

Contra-Variance with generic interfaces

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

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

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

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

Thanks For Attending

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

el-bukhari.com

top related