Generics in .NET Framework (System.Collections.Generic)

While designing a class we don’t need to specify type of the methods of such class and allow someone who uses our class to specify this instead. This is useful if you think of it in two ways. First, we don’t need to use Boxing and Unboxing if we would define our method as objects which in turn reduce resources consumption for these types of operations. Also, error handling becomes more precise. For example if we try to convert or cast Object to String and then to Integer compiler will not know it but during run time we’ll get runtime system error. Generics help us to handle this situation in a better way by letting compiler know about this mismatch during actual compilation
class MyObject
{
    public Object one;
    public Object two;
    public MyObject(Object _oneObject, Object _twoObject)
    {
        one = _oneObject;
        two = _twoObject;
    }
}
class MyGenric<ONE, TWO>
{
    public ONE one;
    public TWO two;
    public Gen(one _one, two _two)
    {
        one = _oneObject;
        two = _twoObject;
    }
}
//Consume objects versus generics
MyObject myObject = new MyObject("Hello, ", "World!");
Console.WriteLine((string)myObject.one + (string)myObject.two);

MyGenerics<string, string> myGeneric = new MyGenerics<string, string>("Hello, ", "World!");>
Console.WriteLine(myGeneric.one + myGeneric.two);

We can constraint Generics classes by doing so we can always guarantee that certain methods are always available. For example we can constraint the generic to the class that implements IComparable like that with keyword “where”: class CompGen<T> where T : IComparable and this will guarantee we’ll be able to use method CompareTo or IComparable interface. We can make classes, interfaces, methods and delegates to be generic.

Good and practical example of Generics can be found in the use of Arrays
Collection<int> myGenericCollection = new Collection<int>();

for (int i = 1; i <= 100; i++)
    myGenericCollection.Add(i);

foreach (int i in myGenericCollection)
{
    //Display value, no boxing / unboxing needed.
}