For training related to .net,OOPS,design patterns, MVC,WCF and .net fundamentals
contact at sukeshmarla@gmail.com or Click Here

21 July 2010

Generics in Dotnet

Generic programming is a style of computer programming in which algorithms are written in terms of to-be-specified-later types that are then instantiated when needed for specific types provided as parameters.

Generic programming is about generalizing software components so that they can be easily reused in a wide variety of situations.

Generics in dotnet
In dot net 1.1 a concept of collections came..
But the problem behind this is they store objects and since everything derives from the base classObject, every type can be put into the collection.There is, therefore, effectively no type checking at all

Worse, each time you take an object out of a collection you must cast it to the correct type, which incurs a performance hit, and makes for ugly code (and if you mis-cast, throws an exception). Further, if you add a value type (e.g., an integer) to the collection, the integer isimplicitly boxed (another performance penalty), and explicitly unboxed when you take it out of the collection (yet another performance penalty and more casting).


Generics To The Rescue

  • Generics are the most powerful feature of C# 2.0
  • Generics allow you to define type-safe classes (or methods/interfaces/strucutures or delegates)without compromising type safety, performance, or productivity.
  • Generics permit classes, structs, interfaces delegates, and methods to be parameterized by the types of data they store and manipulate.
Examples
public class Stack
{
object[] items;
int count;
public void Push(object item) {...}
public object Pop() {...}
}

Here we are using an object array to store the Data...

Stack stack = new Stack();
stack.Push(
new Customer());
Customer c = (Customer)stack.Pop();
stack.push(1);
stack.push("My name is Sukesh");
int i=(int)stack.pop();//we know it will give error but compiler wont have to wait still runtime :(

Now just imagine u can push any value in the stack from integer,float to a complex class object.Storing object provides a little bit flexibility but with drawbacks like
No type safety and performance degradation as we discussed earlier.
so how the generic class will be written?lets move towards it.

public class Stack
{
T[] items;
int count;
public void Push(T item) {...}
public T Pop() {...}
}

When the generic class Stack is used, the actual type to substitute for T is specified. In the following example, int is given as the type argument for T:

Stack<int> stack = new Stack<int>();
stack.Push(3);
int x = stack.Pop();

stack.push("Sukesh");//Type mismatch error-->The Program Not even compile.

It was a breif introduction to generics.

we will discuss in depth about generics (adding constraints,Generics with multiple parameters and lots of other) in later blogs, till then bye bye.