Define list type in C #

Is there a way to use reflection in C # 3.5 to determine the 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> ?

Thank.

+3
source share
2 answers

To add to Lucas's answer, you probably want to get around a bit, making sure you really have List<something>:

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

Edit: The above code says: "What is this list?". To answer "this List<MyObject>?", use the operator isas usual:

isListOfMyObject = customerList is List<MyObject>

Or, if all you have is Type:

isListOfMyObject = typeof<List<MyObject>>.IsAssignableFrom(type)
+7
source
Type[] typeParameters = type.GetGenericArguments();
if( typeParameters.Contains( typeof(Customer) ) )
{
    // do whatever
}
0
source

Source: https://habr.com/ru/post/1756041/


All Articles