The reflection code below returns:
System.Collections.Generic.IList`1[TestReflection.Car] Cars
How can I get the Cars root type through reflection? Not IList<Car> – how can I get Car?
using System;
using System.Reflection;
using System.Collections.Generic;
namespace TestReflection
{
class MainClass
{
public static void Main(string[] args)
{
Type t = typeof(Dealer);
MemberInfo[] mi = t.GetMember("Cars");
Console.WriteLine("{0}", mi[0].ToString());
Console.ReadLine();
}
}
class Dealer
{
public IList<Car> Cars { get; set; }
}
class Car
{
public string CarModel { get; set; }
}
}
The easiest way would be to produce a
PropertyInfothat represented the property in question and then its underlying type viaPropertyInfo.PropertyType. Then it’s just a matter of retrieving the type arguments for this generic type, for which you could useType.GetGenericArguments.