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?
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With