Say that you’ve got IList or List as a property. How do you work out that it is a List, or an IList? Can this be done without relying on trial and error?
The name of the type tends to be something like List`1. Is it reasonable to consider a string hack?
class Program {
public class Class1 {
public int a { get; set; }
public IList<int> list { get; set; }
public List<int> concreteList { get; set; }
}
static void Main(string[] args)
{
Test1();
Test2();
}
private static void Test1()
{
var t = typeof (Class1);
var p = t.GetProperty("list");
if (p.PropertyType.IsInterface && p.PropertyType.IsGenericType)
{
var ps = p.PropertyType.GetGenericArguments();
var underlying = p.PropertyType.GetInterface("IList");
var b = underlying == typeof (IList<>);
}
}
private static void Test2() {
var t = typeof(Class1);
var p = t.GetProperty("concreteList");
if (!p.PropertyType.IsInterface && p.PropertyType.IsGenericType) {
var ps = p.PropertyType.GetGenericArguments();
var underlying3 = p.PropertyType.GetGenericTypeDefinition();
var b = underlying3 == typeof (List<>);
}
}
}
If you can get the property value then testing for its type can be quite straight-forward (see Guffa’s answer). However, if you want to find it out without invoking the property then your code is almost there – for example,
IsGenericTypeindicates that the type is generic – can be open (List<T>) or closed (List<int>).IsGenericTypeDefinitionindicates if the generic type is an open type or not.GetGenericTypeDefinitionon closed/open generic type will return the generic definition (i.e. the open generic type).