Victor
Victor

Reputation: 953

determine List type in C#

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.

Upvotes: 5

Views: 10387

Answers (2)

Tim Robinson
Tim Robinson

Reputation: 54774

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)

Upvotes: 10

&#181;Bio
&#181;Bio

Reputation: 10758

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

Upvotes: 0

Related Questions