tags:

views:

51

answers:

2

Is there any way using reflection in C# 3.5 to determine if type of an object List<MyObject>? For example here:

Type type = customerList.GetType();

//what should I do with type here to determine if customerList is List<Customer> ?

Thanks.

A: 
Type[] typeParameters = type.GetGenericArguments();
if( typeParameters.Contains( typeof(Customer) ) )
{
    // do whatever
}
BioBuckyBall
A: 

To add to Lucas's response, you'll probably want to be a little defensive by making sure that you do in fact have List<something>:

Type type = customerList.GetType();
if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(List<>))
    itemType = type.GetGenericArguments()[0];
else
    // it's not a list at all

Edit: The above code says, 'what kind of list is it?'. To answer 'is this a List<MyObject>?', use the is operator as normal:

isListOfMyObject = customerList is List<MyObject>

Or, if all you have is a Type:

isListOfMyObject = typeof<List<MyObject>>.IsAssignableFrom(type)
Tim Robinson
Thanks for the reply
Victor