Generics was introduced in C# 2.0 to allow the delay of DataType specification in a class or a method. Due to Generics, we are able to write a method or a class that can work with any DataType and whose DataType can be defined later, as per the need. A Generic class can be defined, using angle brackets <>.
Generic class can be defined by putting the <T> sign after the class name.
- public class MyClass<T>
- { }
The example is given below of simple Generic class.
- class Program
- {
- static void Main(string[] args)
- {
- //Instantiating the Generic Class
- //See here we have given the dataType as Int
- //SampleGenericClass<int> intGenericClass = new SampleGenericClass<int>(10);
- SampleGenericClass<string> stringGenericClass = new SampleGenericClass<string>("TEST");
- string value = stringGenericClass.samplegenericMethod("TESTING");
- Console.ReadLine();
- }
- }
- class SampleGenericClass<T>
- {
- private T genericMemberVariable;
- //Constructor Where T can be of any type
- public SampleGenericClass(T value)
- {
- genericMemberVariable = value;
- }
- public T samplegenericMethod(T genericParameter)
- {
- Console.WriteLine("Parameter type: {0}, value: {1}", typeof(T).ToString(), genericParameter);
- Console.WriteLine("Return type: {0}, value: {1}", typeof(T).ToString(), genericMemberVariable);
- return genericMemberVariable;
- }
- public T samplegenericProperty { get; set; }
- }
Output

Here, the code is given below.
- SampleGenericClass<string> stringGenericClass = new SampleGenericClass<string>("TEST");


Join the conversation! Your thoughts help the community grow.