Featured Post

Monday, April 24, 2017

What Are Generics


Generics allow you to define type-safe classes without compromising type safety, performance, or productivity. You implement the server only once as a generic server, while at the same time you can declare and use it with any type. To do that, use the < and > brackets, enclosing a generic type parameter.
(E.G)
// 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>();
    }
}

Benefits:

Ø  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 instead 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 that are used in a generic data type may be obtained at run-time by using reflection.



No comments:

Post a Comment