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)
- {
-
-
-
-
- SampleGenericClass<string> stringGenericClass = new SampleGenericClass<string>("TEST");
-
- string value = stringGenericClass.samplegenericMethod("TESTING");
- Console.ReadLine();
- }
-
-
-
- }
-
- class SampleGenericClass<T>
- {
- private T genericMemberVariable;
-
-
- 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");
We are passing string as a DataType for a class. T. T has been replaced by the string DataType.
The class given above will be seen, as shown below.
- class SampleGenericClass<T>
- {
- private string genericMemberVariable;
-
-
- public SampleGenericClass(string value)
- {
- genericMemberVariable = value;
- }
-
- public string samplegenericMethod(string genericParameter)
- {
- Console.WriteLine("Parameter type: {0}, value: {1}", typeof(string).ToString(), genericParameter);
- Console.WriteLine("Return type: {0}, value: {1}", typeof(T).ToString(), genericMemberVariable);
-
- return genericMemberVariable;
- }
-
- public string samplegenericProperty { get; set; }
- }
It has been replaced with the DataType string. It can be replaced by the DataType passed while initializing the class.
The example given below uses an integer.
- SampleGenericClass<int> intGenericClass = new SampleGenericClass<int>(1);
-
- intGenericClass.samplegenericProperty = 2;
- int result = intGenericClass.samplegenericMethod(3);
Output for this.
We can apply Generics to,
- Interface
- Abstract class
- Class
- Method
- Static method
- Property
- Event
- Delegates
- Operator
Advantages
- It Increases the reusability of the code.
- These are safe types.
- Performance is better because of the removal of boxing and unboxing possibilities.
- Common use of Generic class is to create collection classes.