C# Generics

Generic is a class which allows the user to define classes and methods with the placeholder. Generics were added to version 2.0 of the C# language. The basic idea behind using Generic is to allow type (Integer, String, … etc., and user-defined types) to be a parameter to methods, classes, and interfaces. A primary limitation of collections is the absence of effective type checking. This means that you can put any object in a collection because all classes in the C# programming language extend from the object base class. This compromises type safety and contradicts the basic definition of C# as a type-safe language. In addition, using collections involves a significant performance overhead in the form of implicit and explicit type casting that is required to add or retrieve objects from a collection.


Generic Methods

Generic method type parameter hides the type parameter of Generic classes. CLR will not issue any warnings or errors, when we use the same type parameter name with both generic method and generic class.


A method declared with the type parameters for its return type or parameters is called a generic method.

class DataStore<T> {     
    private T[] _data = new T[10];          
    public void AddOrUpdate(int index, T item)     
    {         
        if(index >= 0 && index < 10)             
            _data[index] = item;     
    }      
    public T GetData(int index)     
    {         
        if(index >= 0 && index < 10)             
            return _data[index];         
        else
            return default(T);     
    } 
} 

Above, the AddorUpdate() and the GetData() methods are generic methods. The actual data type of the item parameter will be specified at the time of instantiating the DataStore<T> class, as shown below.


Example: Generics Method

using System;
					
public class Program
{
	public static void Main()
	{
		DataStore<string> cities = new DataStore<string>();
		cities.AddOrUpdate(0, "Mumbai");
		cities.AddOrUpdate(1, "Chicago");
		cities.AddOrUpdate(2, "London");

		Console.WriteLine(cities.GetData(100));

		DataStore<int> empIds = new DataStore<int>();
		empIds.AddOrUpdate(0, 50);
		empIds.AddOrUpdate(1, 65);
		empIds.AddOrUpdate(2, 89);
		
		Console.WriteLine(empIds.GetData(0));
	}
}

class DataStore<T>
{
    private T[] _data = new T[10];
    
    public void AddOrUpdate(int index, T item