c# reflection in generic method 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: generic method c#

//Swaps the lhs and rhs variables. T is a type given as an argument 
//and can be used in the method like a type. (It doesn't have to be "T", it can
//be anything).

static void Swap<T>(ref T lhs, ref T rhs)
{
    T temp;
    temp = lhs;
    lhs = rhs;
    rhs = temp;
}

public static void TestSwap()
{
    int a = 1;
    int b = 2;

    Swap<int>(ref a, ref b);
    System.Console.WriteLine(a + " " + b);
}