Sunday, December 23, 2007

Introduction to C# Generics

The generics is the best thing that has happened to .Net framework 2.0.Generics are type-safe data structures with no real data type.Generics are really very fast and it is very easy to code.In c++ we have the templates which does the samething but it differs in functionality and capabilities.

Why we need the generics?
Object based class was used to accept any type data and the type casting of data type takes times which results in low performance.The next severe problem with the Object-based solution is type safety. Because the compiler lets you cast anything to and from Object, you lose compile-time type safety.

What Are Generics?

Generics allow you to define type-safe classes without compromising type safety, performance, or productivity.

eg:-
public class Gclass<datatype>
{
public void setdata(DataType x)
{
ArrayList arr = new ArrayList();
arr.Add(x);
}
}

use the <> brackets, enclosing a generic type parameter.

//to double to the arraylist
Gclass<double> dX = new Gclass<double>();
dX.setdata(1.22);

//to add integer to the arraylist
Gclass<int>iX = new Gclass<int>();
iX.setdata(1);


//to add string to the arraylist.
Gclass<string> sX = new Gclass<string>();
sX.setdata("Promothash");

This code will help you to implement generics.