Skip to content

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

Updated: at 02:12 PM

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.

Check out the ORM (Object Relational Mapper) PRISMA. The database access method I use in all my projects