title: How to get the Count property using reflection for Generic types
body: <p>I have a list of objects, of which I cannot know the type of at compile-time.</p>
  
  <p>I need to identify any of these objects where a 'Count' property exists, and get the value if it does.</p>
  
  <p>This code works for simple Collection types:</p>
  
  <pre><code>PropertyInfo countProperty = objectValue.GetType().GetProperty("Count");
   if (countProperty != null)
   {
       int count = (int)countProperty.GetValue(objectValue, null);
   }
  </code></pre>
  
  <p>The problem is that this doesn't work for generic types, such as <code>IDictionary&lt;TKey,TValue&gt;</code>.  In those cases, the 'countProperty' value is returned as null, even though a 'Count' property exists in the instanced object.  </p>
  
  <p>All I want to do is identify any collection/dictionary based object and find the size of it, if it has one. </p>
  
  <p>Edit: as requested, here's the entire listing of code that doesn't work</p>
  
  <pre><code>private static void GetCacheCollectionValues(ref CacheItemInfo item, object cacheItemValue)
  {
      try
          {
          //look for a count property using reflection
          PropertyInfo countProperty = cacheItemValue.GetType().GetProperty("Count");
          if (countProperty != null)
          {
              int count = (int)countProperty.GetValue(cacheItemValue, null);
              item.Count = count;
          }
          else
          {
              //poke around for a 'values' property
              PropertyInfo valuesProperty = cacheItemValue.GetType().GetProperty("Values");
              int valuesCount = -1;
              if (valuesProperty != null)
              {
                  object values = valuesProperty.GetValue(cacheItemValue, null);
                  if (values != null)
                  {
                      PropertyInfo valuesCountProperty = values.GetType().GetProperty("Count");
                      if (countProperty != null)
                      {
                          valuesCount = (int)valuesCountProperty.GetValue(cacheItemValue, null);
                      }
                  }
              }
              if (valuesCount &gt; -1)
                  item.Count = valuesCount;
              else
                  item.Count = -1;
          }
      }
      catch (Exception ex)
      {
          item.Count = -1;
          item.Message = "Exception on 'Count':" + ex.Message;
      }
  }
  </code></pre>
  
  <p>This works OK on simple collections, but not on an object created from a class I have which is derived from <code>Dictionary&lt;TKey,TValue&gt;</code>. Ie </p>
  
  <pre><code>CustomClass : 
      Dictionary&lt;TKey,TValue&gt;
  </code></pre>
  
  <p>CacheItemInfo is just a simple class that contains properties for cache items - ie, key, count, type, expiration datetime</p>