• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

255
Views
check whether a given property type is a typeof(list<>)

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?

about 3 years ago · Santiago Trujillo
2 answers
Answer question

0

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

  • the type is generic by checking its IsGenericType property,
  • the generic type base is System.List<> by checking the result of GetGenericTypeDefinition() against typeof(List<>)
  • type T is the one you want by checking GetGenericArguments()

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 ...
}
about 3 years ago · Santiago Trujillo Report

0

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)

about 3 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error