Home > Net >  check whether a given property type is a typeof(list<>)
check whether a given property type is a typeof(list<>)

Time:12-26

I have three lists something like List<EmpRoles> , List<EmpVisibility> , List<EmpProps>.

Now I want to perform certain operations on them. For this first I have to check whether the property is of type list or not. I have use if block something like below

if ( propertyName == "EmpRoles" || propertyName == "EmpVis" || propertyName == "EmpProps") 

Is there any better way of doing this thing , or is it possible to put some typeof(list<>) conditions. I know typeof(list<>) won't work here. Either i have to use typeof(list)... Can Someone help in making a generic way to identify the list type properties?

CodePudding user response:

Checking that a type is a List<T> requires ensuring that:

If all three conditions are met, you have your type:

var pt = myProperty.PropertyType;
if (pt.IsGenericType &&
    pt.GetGenericTypeDefinition() == typeof(List<>)) {
    var elementType = pt.GetGenericArguments()[0];
    if (elementType == typeof(EmpRoles)) {
        ...
    } else if (elenentType == typeof(EmpVisibility)) {
        ...
    } else if ...
}

CodePudding user response:

You can get generic parameter from list as following

var list = new List<EmpRoles>
var argType = list.GetType().GenericTypeArguments[0]; 

Here in argType you will get typeof(EmpRoles)

  • Related