C Sharp Generics

C# Generics

To define the classes and methods with placeholder or to create general purpose classes and methods, the concept of Generic is used in C#. At the compile time, the placeholders are replaced with specified type by the C# compiler. The angle <> brackets are used for the declaration of a generic class or a generic method.

Example:

using System;  
namespace Example  
{  
    class GenericClass  
    {  
        public GenericClass(T xyz)  
        {  
            Console.WriteLine(xyz);  
        }  
    }  
    class gen  
    {  
        static void Main(string[] args)  
        {  
            GenericClass str   = new GenericClass ("Hello World!!");  
            GenericClass    integer  = new GenericClass(10);  
            GenericClass   character = new GenericClass('V');  
        }  
    }  
}

Output:

Explanation:

In the above example, a generic class is created to deal with any type of data.

Example:

using System;  
namespace Example  
{  
    class GenericClass  
    {  
        public void Show(T xyz)  
        {  
            Console.WriteLine(xyz);  
        }  
    }  
    class gen  
    {  
        static void Main(string[] args)  
        {  
            GenericClass classgen = new GenericClass();  
            classgen.Show("Hello World!!");  
            classgen.Show(10);  
            classgen.Show('V');  
        }  
    }  
}

Output:

Explanation:

In the above example, a generic method is created. Any type of argument can be passed to call this method.

Please Share