Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

determine List type in C#

Tags:

.net-3.5

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.

like image 641
Victor Avatar asked Jan 21 '23 17:01

Victor


1 Answers

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)
like image 70
Tim Robinson Avatar answered Mar 02 '23 23:03

Tim Robinson