Thursday, February 2, 2012

Generics classes Overview


Generic classes and methods combine re-usability, type safety and efficiency also. 
Generics are most commonly used with collections and the methods that operate on them. 


Version 2.0 of the .NET Framework class library provides a new namespace.


System.Collections.Generic, which contains several new generic-based collection classes. 


It is recommended that all applications that target Version 2.0 use the new generic collection classes instead of the older non-generic counterparts such as ArrayList. 


Use generic types to maximize code reuse, type safety, and performance.


The most common use of generics is to create collection classes.


The .NET Framework class library contains several new generic collection classes in the System.Collections.Generic namespace. These should be used whenever possible in place of classes such as ArrayList in the System.Collections namespace.


You can create your own generic interfaces, classes, methods, events and delegates.


Generic classes may be constrained to enable access to methods on particular data types.
Information on the types used in a generic data type may be obtained at run-time by means of reflection.




// type parameter T in angle brackets
public class GenericList<T> 
{
    // The nested class is also generic on T
    private class Node
    {
        // T used in non-generic constructor
        public Node(T t)
        {
            next = null;
            data = t;
        }


        private Node next;
        public Node Next
        {
            get { return next; }
            set { next = value; }
        }
        
        // T as private member data type
        private T data;


        // T as return type of property
        public T Data  
        {
            get { return data; }
            set { data = value; }
        }
    }


    private Node head;
    
    // constructor
    public GenericList() 
    {
        head = null;
    }


    // T as method parameter type:
    public void AddHead(T t) 
    {
        Node n = new Node(t);
        n.Next = head;
        head = n;
    }


    public IEnumerator<T> GetEnumerator()
    {
        Node current = head;


        while (current != null)
        {
            yield return current.Data;
            current = current.Next;
        }
    }
}


As the type of a method parameter in the AddHead method.
As the return type of the public method GetNext and the Data property in the nested Node class.
As the type of the private member data in the nested class.


// Declare the generic class
public class GenericList<T>
{
    void Add(T input) { }
}
class TestGenericList
{
    private class ExampleClass { }
    static void Main()
    {
        // Declare a list of type int
        GenericList<int> list1 = new GenericList<int>();


        // Declare a list of type string
        GenericList<string> list2 = new GenericList<string>();


        // Declare a list of type ExampleClass
        GenericList<ExampleClass> list3 = new GenericList<ExampleClass>();
    }
}
/A generic method is a method that is declared with type parameters, as follows:


static void Swap<T>(ref T lhs, ref T rhs)
{
    T temp;
    temp = lhs;
    lhs = rhs;
    rhs = temp;
}


The following code example shows one way to call the method, using int for the type argument:
public static void TestSwap()
{
    int a = 1;
    int b = 2;


    Swap<int>(ref a, ref b);
    System.Console.WriteLine(a + " " + b);
}
You can also omit the type argument and the compiler will infer it. The following call to Swap is equivalent to the previous call:


Swap(ref a, ref b);


The same rules for type inference apply to static methods as well as instance methods. The compiler is able to infer the type parameters based on the method arguments you pass in; it cannot infer the type parameters solely from a constraint or return value. Therefore type inference does not work with methods that have no parameters. Type inference takes place at compile time before the compiler attempts to resolve any overloaded method signatures. The compiler applies type inference logic to all generic methods that share the same name. In the overload resolution step, the compiler includes only those generic methods on which type inference succeeded.


Within a generic class, non-generic methods can access the class-level type parameters, as follows:


class SampleClass<T>
{
    void Swap(ref T lhs, ref T rhs) { }
}
If you define a generic method that takes the same type parameters as the containing class the compiler will generate warning CS0693 because within the method scope, the argument supplied for the inner T will hide the argument supplied for the outer T. If you require the flexibility of calling a generic class method with type arguments other than the ones provided when the class was instantiated, consider providing another identifier for the method's type parameter, as shown in GenericList2<T> in the following example.
class GenericList<T>
{
    // CS0693
    void SampleMethod<T>() { }
}
class GenericList2<T>
{
    //No warning
    void SampleMethod<U>() { }
}
Use constraints to enable more specialized operations on type parameters in methods. This version of Swap<T>, now called SwapIfGreater<T>, can only be used with type arguments that implement IComparable<T>.
void SwapIfGreater<T>(ref T lhs, ref T rhs) where T : System.IComparable<T>
{
    T temp;
    if (lhs.CompareTo(rhs) > 0)
    {
        temp = lhs;
        lhs = rhs;
        rhs = temp;
    }
}
Generic methods can be overloaded on a number of type parameters. For example, the following methods can all exist in the same class:


void DoWork() { }
void DoWork<T>() { }
void DoWork<T, U>() { }

No comments: