Generics :

May 11, 2011
  • Generics allow us to have type or method which can operate on objects of various types, while providing type safety at the compile time.
  • That means if you define generics class object of type Integer & you are trying to add different type of variable to generic class like String then it will give compile time error.
  • In another sense, if we try to add different types in same list like string and int in a same list then compile time error will be thrown.
  • Generics are available under the namespace System.Collections.Generic.
  • The concept of type parameters is introduce to the .NET Framework with the help of Generics, which makes it possible to design classes & methods which defer the specification of one or more types until that class or method is declared and instantiated by the client code.
public class MyGenericClass { void Add(T val) { } } //Define a class which will consume MyGenericClass class MyGenericClass { static void Main() { // Declare a generic list having int as type MyGenericClass myGenericClassObj1 = new MyGenericClass(); // Declare a generic list of having string as type MyGenericClass myGenericClassObj2 = new MyGenericClass(); } }

Advantages:

  • Generics provide feature of Type Safety & it's performance is faster.
  • Generics can be used to create your own class of collection.
  • Using generic we can create your own generic methods, interfaces, classes, delegates and events.