Search This Blog

Friday, November 4, 2011

WHAT is Generics in c sharp And Why we are using it.????????

Generics:-
                 The Generic is the concept by using which we can provide the type of parameter at the run time.

And also we can provide reuse-ability to the code written in the c# language,Just Example that we can take two data members of the class but at the declaration of the class we have to write or specify that the data type will be  temperary any name will be given to that at the declaration of the class .

But when we are creating object of that class to access it's properties at that time we are providing the type of the parameters which are used by that class.

Here in below example the Type of data is Integer ,String and Example class .

Example:-

public class GenericList<T>
{
    void Add(T input) { }
}
class Program
{
    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>();
    }
}

No comments:

Post a Comment