SlideShare a Scribd company logo
1 of 23
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 Overview ,[object Object],➤  Performance ➤  Type safety ➤  Binary code reuse ➤  Code bloat ➤  Naming guidelines
Performance var list = new ArrayList(); list.Add(44); //  boxing — convert a value type to a reference type int i1 = (int)list[0]; //  unboxing — convert a reference type to //  a value type foreach (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 needed foreach (int i2 in list) { Console.WriteLine(i2); }
Type safety var list = new ArrayList(); list.Add(44); list.Add(&quot;mystring&quot;); list.Add(new MyClass()); foreach (int i in list) { Console.WriteLine(i); } var list = new List<int>(); list.Add(44); list.Add(&quot;mystring&quot;); //  compile time error list.Add(new MyClass()); //  compile time error
binary Code reuse var list = new List<int>(); list.Add(44); var stringList = new List<string>(); stringList.Add(&quot;mystring&quot;); var myClassList = new List<MyClass>(); myClassList.Add(new MyClass());
Code bloat when the generic classes are compiled by the JIT compiler to native code, a new class for every specific value type is created. Reference types share all the same implementation of the same native class.  This is because with reference types, only a 4-byte memory address (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.cs LinkedListObjects/LinkedList.cs LinkedListObjects/Program.cs LinkedListSample/LinkedListNode.cs LinkedListSample/LinkedList.cs LinkedListSample/Program.cs
Generics FeaTures ➤  Default values ➤  Constraints ➤  Inheritance ➤  Static members DocumentManager/DocumentManager.cs
default Values public T GetDocument() { T doc = default(T); lock (this) { doc = documentQueue.Dequeue(); } return doc; }
Constraints DocumentManager/Document.cs DocumentManager/DocumentManager.cs DocumentManager/Program.cs
inheritance public 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 must be 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 members public class StaticDemo<T> { public static int x; } StaticDemo<string>.x = 4; StaticDemo<int>.x = 5; Console.WriteLine(StaticDemo<string>.x); // writes 4
Generic interfaces public interface IComparable<in T> { int CompareTo(T other); } The older, non-generic IComparable interface requires an object with the CompareTo() method. This requires 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-variance Variance/Shape.cs Variance/Rectangle.cs
Covariance with generic interfaces Variance/IIndex.cs Variance/RectangleCollection.cs Variance/Program.cs
Contra-Variance with generic interfaces Variance/IDisplay.cs Variance/ShapeDisplay.cs Variance/Program.cs
generic methods The 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 is not required to assign the generic type with the method call. The generic method can be invoked as simply as non-generic methods: int i = 4; int j = 5; Swap(ref i, ref j);
generic methods example GenericMethods/Account.cs GenericMethods/Program.cs GenericMethods/Algorithm.cs
generic methods with Constraints GenericMethods/Algorithm.cs GenericMethods/Account.cs GenericMethods/IAccount.cs GenericMethods/Program.cs
Thanks For Attending Abed El-Azeem Bukhari (MCPD,MCTS and MCP) el-bukhari.com

More Related Content

What's hot

Type casting in java
Type casting in javaType casting in java
Type casting in javaFarooq Baloch
 
Web application architecture
Web application architectureWeb application architecture
Web application architectureIlio Catallo
 
Abstract Base Class and Polymorphism in C++
Abstract Base Class and Polymorphism in C++Abstract Base Class and Polymorphism in C++
Abstract Base Class and Polymorphism in C++Liju Thomas
 
Under the hood of scala implicits (kl10tch 10.03.2015)
Under the hood of scala implicits (kl10tch 10.03.2015)Under the hood of scala implicits (kl10tch 10.03.2015)
Under the hood of scala implicits (kl10tch 10.03.2015)Alexander Podkhalyuzin
 
Storage classes in c++
Storage classes in c++Storage classes in c++
Storage classes in c++Jaspal Singh
 
Generic Types in Java (for ArtClub @ArtBrains Software)
Generic Types in Java (for ArtClub @ArtBrains Software)Generic Types in Java (for ArtClub @ArtBrains Software)
Generic Types in Java (for ArtClub @ArtBrains Software)Andrew Petryk
 
Storage Class Specifiers in C++
Storage Class Specifiers in C++Storage Class Specifiers in C++
Storage Class Specifiers in C++Reddhi Basu
 
Java Questioner for
Java Questioner for Java Questioner for
Java Questioner for Abhay Korat
 
(7) c sharp introduction_advanvced_features_part_ii
(7) c sharp introduction_advanvced_features_part_ii(7) c sharp introduction_advanvced_features_part_ii
(7) c sharp introduction_advanvced_features_part_iiNico Ludwig
 
Under the hood of scala implicits (Scala eXchange 2014)
Under the hood of scala implicits (Scala eXchange 2014)Under the hood of scala implicits (Scala eXchange 2014)
Under the hood of scala implicits (Scala eXchange 2014)Alexander Podkhalyuzin
 
Overview of c language
Overview of c languageOverview of c language
Overview of c languageshalini392
 

What's hot (20)

07. Virtual Functions
07. Virtual Functions07. Virtual Functions
07. Virtual Functions
 
Lecture 1
Lecture 1Lecture 1
Lecture 1
 
Some basic FP concepts
Some basic FP conceptsSome basic FP concepts
Some basic FP concepts
 
Type casting in java
Type casting in javaType casting in java
Type casting in java
 
Chapter 2
Chapter 2Chapter 2
Chapter 2
 
Web application architecture
Web application architectureWeb application architecture
Web application architecture
 
Abstract Base Class and Polymorphism in C++
Abstract Base Class and Polymorphism in C++Abstract Base Class and Polymorphism in C++
Abstract Base Class and Polymorphism in C++
 
Token and operators
Token and operatorsToken and operators
Token and operators
 
Under the hood of scala implicits (kl10tch 10.03.2015)
Under the hood of scala implicits (kl10tch 10.03.2015)Under the hood of scala implicits (kl10tch 10.03.2015)
Under the hood of scala implicits (kl10tch 10.03.2015)
 
Storage classes in c++
Storage classes in c++Storage classes in c++
Storage classes in c++
 
Generic Types in Java (for ArtClub @ArtBrains Software)
Generic Types in Java (for ArtClub @ArtBrains Software)Generic Types in Java (for ArtClub @ArtBrains Software)
Generic Types in Java (for ArtClub @ArtBrains Software)
 
Storage classes in C
Storage classes in CStorage classes in C
Storage classes in C
 
Storage Class Specifiers in C++
Storage Class Specifiers in C++Storage Class Specifiers in C++
Storage Class Specifiers in C++
 
5.program structure
5.program structure5.program structure
5.program structure
 
Java Questioner for
Java Questioner for Java Questioner for
Java Questioner for
 
(7) c sharp introduction_advanvced_features_part_ii
(7) c sharp introduction_advanvced_features_part_ii(7) c sharp introduction_advanvced_features_part_ii
(7) c sharp introduction_advanvced_features_part_ii
 
Under the hood of scala implicits (Scala eXchange 2014)
Under the hood of scala implicits (Scala eXchange 2014)Under the hood of scala implicits (Scala eXchange 2014)
Under the hood of scala implicits (Scala eXchange 2014)
 
Ppt of c vs c#
Ppt of c vs c#Ppt of c vs c#
Ppt of c vs c#
 
Overview of c language
Overview of c languageOverview of c language
Overview of c language
 
Constructors and Destructors
Constructors and DestructorsConstructors and Destructors
Constructors and Destructors
 

Viewers also liked

Csharp4 arrays and_tuples
Csharp4 arrays and_tuplesCsharp4 arrays and_tuples
Csharp4 arrays and_tuplesAbed Bukhari
 
C# Delegates, Events, Lambda
C# Delegates, Events, LambdaC# Delegates, Events, Lambda
C# Delegates, Events, LambdaJussi Pohjolainen
 
12 events and delegates
12   events and delegates12   events and delegates
12 events and delegatesTuan Ngo
 
Delegates and events
Delegates and eventsDelegates and events
Delegates and eventsIblesoft
 
C# Delegates and Event Handling
C# Delegates and Event HandlingC# Delegates and Event Handling
C# Delegates and Event HandlingJussi Pohjolainen
 

Viewers also liked (8)

Csharp4 arrays and_tuples
Csharp4 arrays and_tuplesCsharp4 arrays and_tuples
Csharp4 arrays and_tuples
 
Delegates in C#
Delegates in C#Delegates in C#
Delegates in C#
 
Csharp4 basics
Csharp4 basicsCsharp4 basics
Csharp4 basics
 
C# Delegates, Events, Lambda
C# Delegates, Events, LambdaC# Delegates, Events, Lambda
C# Delegates, Events, Lambda
 
12 events and delegates
12   events and delegates12   events and delegates
12 events and delegates
 
Delegates and events
Delegates and eventsDelegates and events
Delegates and events
 
C# Delegates and Event Handling
C# Delegates and Event HandlingC# Delegates and Event Handling
C# Delegates and Event Handling
 
Delegates and events
Delegates and events   Delegates and events
Delegates and events
 

Similar to Csharp4 generics

Jdk1.5 Features
Jdk1.5 FeaturesJdk1.5 Features
Jdk1.5 Featuresindia_mani
 
Generic Programming seminar
Generic Programming seminarGeneric Programming seminar
Generic Programming seminarGautam Roy
 
Java Generics
Java GenericsJava Generics
Java Genericsjeslie
 
.NET 2015: Будущее рядом
.NET 2015: Будущее рядом.NET 2015: Будущее рядом
.NET 2015: Будущее рядомAndrey Akinshin
 
Clean code _v2003
 Clean code _v2003 Clean code _v2003
Clean code _v2003R696
 
Java New Programming Features
Java New Programming FeaturesJava New Programming Features
Java New Programming Featurestarun308
 
Csharp In Detail Part2
Csharp In Detail Part2Csharp In Detail Part2
Csharp In Detail Part2Mohamed Krar
 
Advanced c#
Advanced c#Advanced c#
Advanced c#saranuru
 
Getting Started - Console Program and Problem Solving
Getting Started - Console Program and Problem SolvingGetting Started - Console Program and Problem Solving
Getting Started - Console Program and Problem SolvingHock Leng PUAH
 
SPF Getting Started - Console Program
SPF Getting Started - Console ProgramSPF Getting Started - Console Program
SPF Getting Started - Console ProgramHock Leng PUAH
 
C# / Java Language Comparison
C# / Java Language ComparisonC# / Java Language Comparison
C# / Java Language ComparisonRobert Bachmann
 
The Kotlin Programming Language
The Kotlin Programming LanguageThe Kotlin Programming Language
The Kotlin Programming Languageintelliyole
 
Swift Programming
Swift ProgrammingSwift Programming
Swift ProgrammingCodemotion
 
3 functions and class
3   functions and class3   functions and class
3 functions and classtrixiacruz
 

Similar to Csharp4 generics (20)

Jdk1.5 Features
Jdk1.5 FeaturesJdk1.5 Features
Jdk1.5 Features
 
Generic Programming seminar
Generic Programming seminarGeneric Programming seminar
Generic Programming seminar
 
Java Generics
Java GenericsJava Generics
Java Generics
 
.NET 2015: Будущее рядом
.NET 2015: Будущее рядом.NET 2015: Будущее рядом
.NET 2015: Будущее рядом
 
Clean code _v2003
 Clean code _v2003 Clean code _v2003
Clean code _v2003
 
Java generics
Java genericsJava generics
Java generics
 
Java New Programming Features
Java New Programming FeaturesJava New Programming Features
Java New Programming Features
 
Csharp In Detail Part2
Csharp In Detail Part2Csharp In Detail Part2
Csharp In Detail Part2
 
Notes(1).pptx
Notes(1).pptxNotes(1).pptx
Notes(1).pptx
 
Advanced c#
Advanced c#Advanced c#
Advanced c#
 
Java Generics - by Example
Java Generics - by ExampleJava Generics - by Example
Java Generics - by Example
 
Java Generics - by Example
Java Generics - by ExampleJava Generics - by Example
Java Generics - by Example
 
Getting Started - Console Program and Problem Solving
Getting Started - Console Program and Problem SolvingGetting Started - Console Program and Problem Solving
Getting Started - Console Program and Problem Solving
 
SPF Getting Started - Console Program
SPF Getting Started - Console ProgramSPF Getting Started - Console Program
SPF Getting Started - Console Program
 
C# / Java Language Comparison
C# / Java Language ComparisonC# / Java Language Comparison
C# / Java Language Comparison
 
Java 5 Features
Java 5 FeaturesJava 5 Features
Java 5 Features
 
The Kotlin Programming Language
The Kotlin Programming LanguageThe Kotlin Programming Language
The Kotlin Programming Language
 
Swift Introduction
Swift IntroductionSwift Introduction
Swift Introduction
 
Swift Programming
Swift ProgrammingSwift Programming
Swift Programming
 
3 functions and class
3   functions and class3   functions and class
3 functions and class
 

More from Abed Bukhari

Csharp4 delegates lambda_and_events
Csharp4 delegates lambda_and_eventsCsharp4 delegates lambda_and_events
Csharp4 delegates lambda_and_eventsAbed Bukhari
 
Csharp4 strings and_regular_expressions
Csharp4 strings and_regular_expressionsCsharp4 strings and_regular_expressions
Csharp4 strings and_regular_expressionsAbed Bukhari
 
Csharp4 operators and_casts
Csharp4 operators and_castsCsharp4 operators and_casts
Csharp4 operators and_castsAbed Bukhari
 
Csharp4 objects and_types
Csharp4 objects and_typesCsharp4 objects and_types
Csharp4 objects and_typesAbed Bukhari
 
Csharp4 inheritance
Csharp4 inheritanceCsharp4 inheritance
Csharp4 inheritanceAbed Bukhari
 
Whats new in_csharp4
Whats new in_csharp4Whats new in_csharp4
Whats new in_csharp4Abed Bukhari
 

More from Abed Bukhari (6)

Csharp4 delegates lambda_and_events
Csharp4 delegates lambda_and_eventsCsharp4 delegates lambda_and_events
Csharp4 delegates lambda_and_events
 
Csharp4 strings and_regular_expressions
Csharp4 strings and_regular_expressionsCsharp4 strings and_regular_expressions
Csharp4 strings and_regular_expressions
 
Csharp4 operators and_casts
Csharp4 operators and_castsCsharp4 operators and_casts
Csharp4 operators and_casts
 
Csharp4 objects and_types
Csharp4 objects and_typesCsharp4 objects and_types
Csharp4 objects and_types
 
Csharp4 inheritance
Csharp4 inheritanceCsharp4 inheritance
Csharp4 inheritance
 
Whats new in_csharp4
Whats new in_csharp4Whats new in_csharp4
Whats new in_csharp4
 

Csharp4 generics

  • 1. Abed El-Azeem Bukhari (MCPD,MCTS and MCP) el-bukhari.com
  • 2. 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
  • 3.
  • 4. Performance var list = new ArrayList(); list.Add(44); // boxing — convert a value type to a reference type int i1 = (int)list[0]; // unboxing — convert a reference type to // a value type foreach (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 needed foreach (int i2 in list) { Console.WriteLine(i2); }
  • 5. Type safety var list = new ArrayList(); list.Add(44); list.Add(&quot;mystring&quot;); list.Add(new MyClass()); foreach (int i in list) { Console.WriteLine(i); } var list = new List<int>(); list.Add(44); list.Add(&quot;mystring&quot;); // compile time error list.Add(new MyClass()); // compile time error
  • 6. binary Code reuse var list = new List<int>(); list.Add(44); var stringList = new List<string>(); stringList.Add(&quot;mystring&quot;); var myClassList = new List<MyClass>(); myClassList.Add(new MyClass());
  • 7. Code bloat when the generic classes are compiled by the JIT compiler to native code, a new class for every specific value type is created. Reference types share all the same implementation of the same native class. This is because with reference types, only a 4-byte memory address (with 32-bit systems) is needed within the generic instantiated class to reference a reference type.
  • 8. naming guidelines Generic type names should be prefixed with the letter T .
  • 9. Creating Generic Classes LinkedListObjects/LinkedListNode.cs LinkedListObjects/LinkedList.cs LinkedListObjects/Program.cs LinkedListSample/LinkedListNode.cs LinkedListSample/LinkedList.cs LinkedListSample/Program.cs
  • 10. Generics FeaTures ➤ Default values ➤ Constraints ➤ Inheritance ➤ Static members DocumentManager/DocumentManager.cs
  • 11. default Values public T GetDocument() { T doc = default(T); lock (this) { doc = documentQueue.Dequeue(); } return doc; }
  • 13. inheritance public 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 must be specified, as in this case: public class Base<T> { } public class Derived<T>: Base<string> { }
  • 14. 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; } }
  • 15. static members public class StaticDemo<T> { public static int x; } StaticDemo<string>.x = 4; StaticDemo<int>.x = 5; Console.WriteLine(StaticDemo<string>.x); // writes 4
  • 16. Generic interfaces public interface IComparable<in T> { int CompareTo(T other); } The older, non-generic IComparable interface requires an object with the CompareTo() method. This requires 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); } //...
  • 17. Covariance and Contra-variance Variance/Shape.cs Variance/Rectangle.cs
  • 18. Covariance with generic interfaces Variance/IIndex.cs Variance/RectangleCollection.cs Variance/Program.cs
  • 19. Contra-Variance with generic interfaces Variance/IDisplay.cs Variance/ShapeDisplay.cs Variance/Program.cs
  • 20. generic methods The 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 is not required to assign the generic type with the method call. The generic method can be invoked as simply as non-generic methods: int i = 4; int j = 5; Swap(ref i, ref j);
  • 21. generic methods example GenericMethods/Account.cs GenericMethods/Program.cs GenericMethods/Algorithm.cs
  • 22. generic methods with Constraints GenericMethods/Algorithm.cs GenericMethods/Account.cs GenericMethods/IAccount.cs GenericMethods/Program.cs
  • 23. Thanks For Attending Abed El-Azeem Bukhari (MCPD,MCTS and MCP) el-bukhari.com

Editor's Notes

  1. //LinkedListObjects/LinkedListNode.cs namespace Najah.ILoveCsharp.Generics { public class LinkedListNode { public LinkedListNode(object value) { this.Value = value; } public object Value { get; private set; } public LinkedListNode Next { get; internal set; } public LinkedListNode Prev { get; internal set; } } } //LinkedListObjects/LinkedList.cs using System.Collections; namespace Najah.ILoveCsharp.Generics { public class LinkedList : IEnumerable { public LinkedListNode First { get; private set; } public LinkedListNode Last { get; private set; } public LinkedListNode AddLast(object node) { var newNode = new LinkedListNode(node); if (First == null) { First = newNode; Last = First; } else { Last.Next = newNode; Last = newNode; } return newNode; } public IEnumerator GetEnumerator() { LinkedListNode current = First; while (current != null) { yield return current.Value; current = current.Next; } } } } //LinkedListObjects/Program.cs using System; namespace Najah.ILoveCsharp.Generics { class Program { static void Main() { var list1 = new LinkedList(); list1.AddLast(2); list1.AddLast(4); list1.AddLast(&amp;quot;6&amp;quot;); foreach (int i in list1) { Console.WriteLine(i); } } } } //LinkedListSample/LinkedListNode.cs namespace Najah.ILoveCsharp.Generics { public class LinkedListNode&lt;T&gt; { public LinkedListNode(T value) { this.Value = value; } public T Value { get; private set; } public LinkedListNode&lt;T&gt; Next { get; internal set; } public LinkedListNode&lt;T&gt; Prev { get; internal set; } } } //LinkedListSample/LinkedList.cs using System.Collections; using System.Collections.Generic; namespace Najah.ILoveCsharp.Generics { public class LinkedList&lt;T&gt; : IEnumerable&lt;T&gt; { public LinkedListNode&lt;T&gt; First { get; private set; } public LinkedListNode&lt;T&gt; Last { get; private set; } public LinkedListNode&lt;T&gt; AddLast(T node) { var newNode = new LinkedListNode&lt;T&gt;(node); if (First == null) { First = newNode; Last = First; } else { Last.Next = newNode; Last = newNode; } return newNode; } public IEnumerator&lt;T&gt; GetEnumerator() { LinkedListNode&lt;T&gt; current = First; while (current != null) { yield return current.Value; current = current.Next; } } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } } //LinkedListSample/Program.cs using System; namespace Najah.ILoveCsharp.Generics { class Program { static void Main() { var list2 = new LinkedList&lt;int&gt;(); list2.AddLast(1); list2.AddLast(3); list2.AddLast(5); foreach (int i in list2) { Console.WriteLine(i); } var list3 = new LinkedList&lt;string&gt;(); list3.AddLast(&amp;quot;2&amp;quot;); list3.AddLast(&amp;quot;four&amp;quot;); list3.AddLast(&amp;quot;foo&amp;quot;); foreach (string s in list3) { Console.WriteLine(s); } } } }
  2. // DocumentManager/DocumentManager.cs using System; using System.Collections.Generic; namespace Najah.ILoveCsharp.Generics { public class DocumentManager&lt;TDocument&gt; where TDocument : IDocument { private readonly Queue&lt;TDocument&gt; documentQueue = new Queue&lt;TDocument&gt;(); public void AddDocument(TDocument doc) { lock (this) { documentQueue.Enqueue(doc); } } public bool IsDocumentAvailable { get { return documentQueue.Count &gt; 0; } } public void DisplayAllDocuments() { foreach (TDocument doc in documentQueue) { Console.WriteLine(doc.Title); } } public TDocument GetDocument() { TDocument doc = default(TDocument); lock (this) { doc = documentQueue.Dequeue(); } return doc; } } }
  3. //DocumentManager/Document.cs namespace Najah.ILoveCsharp.Generics { public interface IDocument { string Title { get; set; } string Content { get; set; } } public class Document : IDocument { public Document() { } public Document(string title, string content) { this.Title = title; this.Content = content; } public string Title { get; set; } public string Content { get; set; } } } //DocumentManager/DocumentManager.cs using System; using System.Collections.Generic; namespace Najah.ILoveCsharp.Generics { public class DocumentManager&lt;TDocument&gt; where TDocument : IDocument { private readonly Queue&lt;TDocument&gt; documentQueue = new Queue&lt;TDocument&gt;(); public void AddDocument(TDocument doc) { lock (this) { documentQueue.Enqueue(doc); } } public bool IsDocumentAvailable { get { return documentQueue.Count &gt; 0; } } public void DisplayAllDocuments() { foreach (TDocument doc in documentQueue) { Console.WriteLine(doc.Title); } } public TDocument GetDocument() { TDocument doc = default(TDocument); lock (this) { doc = documentQueue.Dequeue(); } return doc; } } } //DocumentManager/Program.cs using System; namespace Najah.ILoveCsharp.Generics { class Program { static void Main() { var dm = new DocumentManager&lt;Document&gt;(); dm.AddDocument(new Document(&amp;quot;Title A&amp;quot;, &amp;quot;Sample A&amp;quot;)); dm.AddDocument(new Document(&amp;quot;Title B&amp;quot;, &amp;quot;Sample B&amp;quot;)); dm.DisplayAllDocuments(); if (dm.IsDocumentAvailable) { Document d = dm.GetDocument(); Console.WriteLine(d.Content); } } } }
  4. //Variance/Shape.cs using System; namespace Najah.ILoveCsharp.Generics { public class Shape { public double Width { get; set; } public double Height { get; set; } public override string ToString() { return String.Format(&amp;quot;Width: {0}, Height: {1}&amp;quot;, Width, Height); } } } //Variance/Rectangle.cs namespace Najah.ILoveCsharp.Generics { public class Rectangle : Shape { } }
  5. //Variance/IIndex.cs namespace Najah.ILoveCsharp.Generics { // covariant public interface IIndex&lt;out T&gt; { T this[int index] { get; } int Count { get; } } } //Variance/RectangleCollection.cs using System; namespace Najah.ILoveCsharp.Generics { public class RectangleCollection : IIndex&lt;Rectangle&gt; { private Rectangle[] data = new Rectangle[3] { new Rectangle { Height=2, Width=5}, new Rectangle { Height=3, Width=7}, new Rectangle { Height=4.5, Width=2.9} }; public static RectangleCollection GetRectangles() { return new RectangleCollection(); } public Rectangle this[int index] { get { if (index &lt; 0 || index &gt; data.Length) throw new ArgumentOutOfRangeException(&amp;quot;index&amp;quot;); return data[index]; } } public int Count { get { return data.Length; } } } } //Variance/Program.cs using System; namespace Najah.ILoveCsharp.Generics { class Program { static void Main() { IIndex&lt;Rectangle&gt; rectangles = RectangleCollection.GetRectangles(); IIndex&lt;Shape&gt; shapes = rectangles; for (int i = 0; i &lt; shapes.Count; i++) { Console.WriteLine(shapes[i]); } IDisplay&lt;Shape&gt; shapeDisplay = new ShapeDisplay(); IDisplay&lt;Rectangle&gt; rectangleDisplay = shapeDisplay; rectangleDisplay.Show(rectangles[0]); } } }
  6. //Variance/IDisplay.cs namespace Najah.ILoveCsharp.Generics { // contra-variant public interface IDisplay&lt;in T&gt; { void Show(T item); } } //Variance/ShapeDisplay.cs using System; namespace Najah.ILoveCsharp.Generics { public class ShapeDisplay : IDisplay&lt;Shape&gt; { public void Show(Shape s) { Console.WriteLine(&amp;quot;{0} Width: {1}, Height: {2}&amp;quot;, s.GetType().Name, s.Width, s.Height); } } } //Variance/Program.cs using System; namespace Najah.ILoveCsharp.Generics { class Program { static void Main() { IIndex&lt;Rectangle&gt; rectangles = RectangleCollection.GetRectangles(); IIndex&lt;Shape&gt; shapes = rectangles; for (int i = 0; i &lt; shapes.Count; i++) { Console.WriteLine(shapes[i]); } IDisplay&lt;Shape&gt; shapeDisplay = new ShapeDisplay(); IDisplay&lt;Rectangle&gt; rectangleDisplay = shapeDisplay; rectangleDisplay.Show(rectangles[0]); } } }
  7. // GenericMethods/Account.cs using System; namespace Najah.ILoveCsharp.Generics { public interface IAccount { decimal Balance { get; } string Name { get; } } public class Account : IAccount { public string Name { get; private set; } public decimal Balance { get; private set; } public Account(string name, Decimal balance) { this.Name = name; this.Balance = balance; } } } //GenericMethods/Program.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Najah.ILoveCsharp.Generics { class Program { static void Main() { var accounts = new List&lt;Account&gt;() { new Account(&amp;quot;Christian&amp;quot;, 1500), new Account(&amp;quot;Stephanie&amp;quot;, 2200), new Account(&amp;quot;Angela&amp;quot;, 1800) }; decimal amount = Algorithm.AccumulateSimple(accounts); amount = Algorithm.Accumulate(accounts); amount = Algorithm.Accumulate&lt;Account, decimal&gt;(accounts, (item, sum) =&gt; sum += item.Balance); } } } //GenericMethods/Algorithm.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Najah.ILoveCsharp.Generics { public static class Algorithm { public static decimal AccumulateSimple(IEnumerable&lt;Account&gt; source) { decimal sum = 0; foreach (Account a in source) { sum += a.Balance; } return sum; } public static decimal Accumulate&lt;TAccount&gt;(IEnumerable&lt;TAccount&gt; source) where TAccount : IAccount { decimal sum = 0; foreach (TAccount a in source) { sum += a.Balance; } return sum; } public static T2 Accumulate&lt;T1, T2&gt;(IEnumerable&lt;T1&gt; source, Func&lt;T1, T2, T2&gt; action) { T2 sum = default(T2); foreach (T1 item in source) { sum = action(item, sum); } return sum; } } }
  8. //GenericMethods/Algorithm.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Najah.ILoveCsharp.Generics { public static class Algorithm { public static decimal AccumulateSimple(IEnumerable&lt;Account&gt; source) { decimal sum = 0; foreach (Account a in source) { sum += a.Balance; } return sum; } public static decimal Accumulate&lt;TAccount&gt;(IEnumerable&lt;TAccount&gt; source) where TAccount : IAccount { decimal sum = 0; foreach (TAccount a in source) { sum += a.Balance; } return sum; } public static T2 Accumulate&lt;T1, T2&gt;(IEnumerable&lt;T1&gt; source, Func&lt;T1, T2, T2&gt; action) { T2 sum = default(T2); foreach (T1 item in source) { sum = action(item, sum); } return sum; } } } //GenericMethods/Account.cs using System; namespace Najah.ILoveCsharp.Generics { public interface IAccount { decimal Balance { get; } string Name { get; } } public class Account : IAccount { public string Name { get; private set; } public decimal Balance { get; private set; } public Account(string name, Decimal balance) { this.Name = name; this.Balance = balance; } } } //GenericMethods/Program.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Najah.ILoveCsharp.Generics { class Program { static void Main() { var accounts = new List&lt;Account&gt;() { new Account(&amp;quot;Christian&amp;quot;, 1500), new Account(&amp;quot;Stephanie&amp;quot;, 2200), new Account(&amp;quot;Angela&amp;quot;, 1800) }; decimal amount = Algorithm.AccumulateSimple(accounts); amount = Algorithm.Accumulate(accounts); amount = Algorithm.Accumulate&lt;Account, decimal&gt;(accounts, (item, sum) =&gt; sum += item.Balance); } } }