Wednesday, July 21, 2010

Generics

What is generic:

We can refer to a class, where we don't force it to be related to any specific Type, but we can still perform work with it in a Type-Safe manner. A perfect example of where we would need Generics is in dealing with collections of items (integers, strings, Orders etc.). We can create a generic collection than can handle any Type in a generic and Type-Safe manner. For example, we can have a single array class that we can use to store a list of Users or even a list of Products, and when we actually use it, we will be able to access the items in the collection directly as a list of Users or Products, and not as objects (with boxing/unboxing, casting).

Syntax:

GenericClass<T> = new GenericClass<T>()

Where T is the datatype that want to list, and GenericClass is the Generic Class which will wrap our desired datatype.

This Generic Class can be our own custom Generic Class or the ones provided by the .Net Framework.

Benefits of Generics:

1) Technically, T gets replaced by the datatype at compile type. And that's the reason why a compile time error occurs when casting is not done properly, it will be an InvalidCast Exception while using ArrayLists. Thus Generics enforce type checking at compile time only, making life less difficult
2) T is "replaced" by our datatype at comile time only so, no time and resources are wasted in boxing and unboxing the objects
3) Generics got rid of disadvantage of array list by avoiding the type casting.

With whom to use generics:

Stack (First in, Last out)
Queue (First In, First out)
List

Example:


public class Col<T> {
T t;
public T Val{get{return t;}set{t=value;}}
}

public class ColMain {
public static void Main() {
//create a string version of our generic class
Col<string> mystring = new Col<string>();
//set the value
mystring.Val = "hello";

//output that value
System.Console.WriteLine(mystring.Val);
//output the value's type
System.Console.WriteLine(mystring.Val.GetType());

//create another instance of our generic class, using a different type
Col<int> myint = new Col<int>();
//load the value
myint.Val = 5;
//output the value
System.Console.WriteLine(myint.Val);
//output the value's type
System.Console.WriteLine(myint.Val.GetType());

}
}

When we compile the two classes above and then run them, we will see the following output:

hello
System.String
5
System.Int32

Even though we used the same class to actually hold our string and int, it keeps their original type intact. That is, we are not going to and from a System.Object type just to hold them.

No comments:

Post a Comment