Reflection with Generics
using System;
using System.Reflection;
public class Program
{
static void Main()
{
Type type;
type = typeof(System.Nullable<>);
Console.WriteLine(type.ContainsGenericParameters);
Console.WriteLine(type.IsGenericType);
type = typeof(System.Nullable<DateTime>);
Console.WriteLine(!type.ContainsGenericParameters);
Console.WriteLine(type.IsGenericType);
}
}
Type: MakeGenericType
using System;
using System.Collections.Generic;
public class MainClass
{
static void Main() {
IList<int> intList = (IList<int>) CreateClosedType<int>( typeof(List<>) );
IList<double> doubleList = (IList<double>) CreateClosedType<double>( typeof(List<>) );
Console.WriteLine( intList );
Console.WriteLine( doubleList );
}
static object CreateClosedType<T>( Type genericType ) {
Type[] typeArguments = {
typeof( T )
};
Type closedType = genericType.MakeGenericType( typeArguments );
return Activator.CreateInstance( closedType );
}
}
System.Collections.Generic.List`1[System.Int32]
System.Collections.Generic.List`1[System.Double]
Using Reflection with Generic Types
using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
Stack<int> s = new Stack<int>();
Type t = s.GetType();
foreach(Type types in t.GetGenericArguments())
{
System.Console.WriteLine(
"Type parameter: " + types.FullName);
}
// ...
}
}