Reflection and Generics
On my current project I had the need to iterate through the properties of an object with reflection and to check if one of the properties is a generic List type, e.g. IList<int>, IList<Customer>, etc. To check through reflection on a generic type, you need to use the GetGenericTypeDefinition method.
[csharp]
foreach (PropertyInfo propertyInfo in entity.GetType().GetProperties())
{
if (propertyInfo.PropertyType.IsGenericType &&
typeof(List<>).IsAssignableFrom
(propertyInfo.PropertyType.GetGenericTypeDefinition()))
{
IEnumerable enumerable = propertyInfo.GetValue(entity, null) as IEnumerable;
IEnumerator enumerator = enumerable.GetEnumerator();
while (enumerator.MoveNext())
{
// do something
}
}
}
[/csharp]
Social Share
One Comment
Leave a Reply
You must be logged in to post a comment.

Hi Delarou,
SuperFandango is a .NET(mainly) and database driven applications specialist company based in Bruxelles.
At the moment, we have a need for extra .net/sql server/ classic asp + vb6 skills.
We came across you via some user group listing.
We would like to get a copy of your CV along with your contact details (email and phone). So thanks to email them to michael.finlan@superfandango.com .
If you know any people with Microsoft Technology skills that are looking for a contract or an employee position, could you be so kind as to forward them our contact details.
Thanks and best regards,
Michael FINLAN
8 Av. du GEAI
1170 Watermael-Boitsfort
Belgium
Tel/Fax: +32 2 742 0587
GSM: +32 486 423 697
http://www.superfandango.com
michael.finlan@superfandango.com