c# generic using a type code example

Example 1: c# reflection create generic type

Type generic = typeof(Dictionary<,>);

// Create an array of types to substitute for the type parameters of Dictionary. The key is of type string, and the type to be contained in the Dictionary is Test.
Type[] typeArgs = { typeof(string), typeof(Test) };

// Create a Type object representing the constructed generic type.
Type constructed = generic.MakeGenericType(typeArgs);

var instance = Activator.CreateInstance(constructedType);

Example 2: generics in c#

class MyGenericClass<T>
{
    private T genericMemberVariable;

    public MyGenericClass(T value)
    {
        genericMemberVariable = value;
    }

    public T genericMethod(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 genericProperty { get; set; }
}

Example 3: generics in c#

class DataStore<T>
{
    public T Data { get; set; }
}