May
2
Written by:
Javier Callico
5/2/2011
This is one of these things that I keep forgetting how to do and end up having to search my code library every time.
The code below is particularly useful when you don’t know until runtime the exact type of the type parameter.
namespace Callicode.Samples.Generics.CreateInstance
{
using System;
using System.Collections.Generic;
public class Program
{
private static void Main(string[] args)
{
Console.WriteLine("Creating instance of type List<string> and capacity 50.");
var instance = CreateInstanceOfType(typeof(List<>), typeof(string), 50);
Console.WriteLine(string.Format("Type: {0}", instance.GetType()));
Console.WriteLine(string.Format("Capacity: {0}", ((List<string>)instance).Capacity));
Console.WriteLine("Creating instance of type List<int> and capacity 30.");
instance = CreateInstanceOfType(typeof(List<>), typeof(int), 30);
Console.WriteLine(string.Format("Type: {0}", instance.GetType()));
Console.WriteLine(string.Format("Capacity: {0}", ((List<int>)instance).Capacity));
Console.ReadKey(true);
}
private static object CreateInstanceOfType(Type genericType, Type resultType, params object[] args)
{
Type invokerType = genericType.MakeGenericType(resultType);
return Activator.CreateInstance(invokerType, args);
}
}
}