C# generic

http‮s‬://www.theitroad.com

Generics in C# allow you to create type-safe classes, structures, interfaces, methods, and delegates that can work with different data types. They provide a way to define a class or method without specifying the data type it works with until it is used in the program. This makes your code more reusable and flexible.

Using generics, you can write a class that can work with any data type, such as List<T> that can store any type of object in the list. The 'T' in List<T> is a type parameter, which is replaced with the actual data type when the list is created.

For example, consider the following generic class:

public class MyGenericClass<T>
{
    private T myVar;
    
    public T MyProperty
    {
        get { return myVar; }
        set { myVar = value; }
    }
    
    public void MyMethod(T arg)
    {
        // Method implementation
    }
}

In the above class, the 'T' is a type parameter that is replaced with an actual data type when an instance of the class is created. The class has a property MyProperty and a method MyMethod that both work with the same data type.

To create an instance of the class for a specific data type, you would do the following:

MyGenericClass<int> myInt = new MyGenericClass<int>();
myInt.MyProperty = 10;
myInt.MyMethod(20);

In the above example, 'int' is the data type that is used to replace the 'T' in the MyGenericClass<T> class. The instance of the class is created for the 'int' data type and the MyProperty and MyMethod both work with 'int' data type.

Using generics, you can write more flexible and reusable code that can work with different data types without having to rewrite the same code for each data type.