Using Reflection in C# to Figure Out if an Integer List Has Values

So, I’ve struggled some with this and did not have much help with searching.

Here is the problem.

You have a declaration that looks like this:

   1: public partial class CompanyQuery   {
   2:       public List<int> CompanyTypeIds { get; set; }
   3: }

Then, you need to figure out if CompanyTypeIds is populated using reflection.

Here is the code:

   1: CompanyQuery query = new CompanyQuery;
   2: query.CompanyTypeIds = new List<int> {1,2,3,4}
   3:  
   4: foreach (var info in typeof(CompanyQuery).GetProperties())
   5:            {
   6:                 object[] attributes = info.GetCustomAttributes(typeof(ForceNoCompileColumnAttribute), true);
   7:                 if (attributes.Length > 0)
   8:                 {
   9:                     object value = info.GetValue(query, null);
  10:                     if (value != null && value.GetType() == (new List<int>()).GetType())
  11:                     {
  12:                         if (((List<int>)value).Count > 0)
  13:                         {
  14:                             forceNoCompile = true;
  15:                         }
  16:                     }
  17:                     else if (value != null)
  18:                     {
  19:                         forceNoCompile = true;
  20:                     }
  21:                 }
  22:            }
  23:  

That’s basically it.

Hope this helps.

About Peter Kellner

Peter is a software professional specializing in mobile and web technologies. He has also been a Microsoft MVP for the past 7 years. To read more about Peter Kellner and his experience click here. For information about how Peter Kellner might be able to help you with your project click here.

Follow me:


Comments

  1. Thanks Geoff for the tip. My problem is that I don’t know ahead of time it is of type List. Is there a way around that?

  2. geoffrey.mcgill says:

    Here’s a general purpose Lambda Expression Extension Method that simplifies the process of getting a Property value. This should also perform better.

    Extension Method
    —————–
    public static Func GetProperty(this Type self, string name)
    {
    ParameterExpression parameter = Expression.Parameter(typeof(X), “obj”);
    MemberExpression property = Expression.Property(parameter, name);
    return (Func)Expression.Lambda(typeof(Func), property, parameter).Compile();
    }

    Usage
    ——————–
    CompanyQuery query = new CompanyQuery { CompanyTypeIds = new List { 1, 2, 3, 4 } };

    Type type = typeof(CompanyQuery);

    Func<CompanyQuery, List> getList = type.GetProperty<CompanyQuery, List>(“CompanyTypeIds”);

    List ids = getList(query);

    bool forceNoCompile = (ids != null && ids.Count > 0);

    Hope this helps.

Follow

Get every new post delivered to your Inbox

Join other followers: