Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check If type is a list returns false

Tags:

c#

list

generics

I was trying to process a generic class with properties that are List<T>. However it does not work when checking the property using IsAssignableFrom.

Code Snippet:

var type = model.GetType();

var properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
int colorIndex = 0;

foreach (var property in properties)
{
    if (typeof(List<>).IsAssignableFrom(property.PropertyType))
    {
        //codes here

    }
}

Am I missing something here? Why is it not treating the property as List even it is a list?

like image 347
rpmansion Avatar asked Dec 25 '22 07:12

rpmansion


1 Answers

In your model object you have properties with specific types, for example List<string>, List<int> or something similar. I your code however you are testing for open generic type. These types are not the same, so you do not get a match in if statement. To fix that you should use function GetGenericTypeDefinition() to get underlying open generic type:

foreach (var property in properties)
{
    if (property.PropertyType.IsGenericType && 
        typeof(List<>).IsAssignableFrom(property.PropertyType.GetGenericTypeDefinition()))
    {
        //codes here

    }
}
like image 96
dotnetom Avatar answered Dec 29 '22 06:12

dotnetom