title: How do I compare types when using generics?
body: <p>I am trying to derive the type of an object at runtime.  Specifically I need to know two things whether it implements ICollection or IDto.  Currently my only solution I have been able to find is this:</p>
  
  <pre><code>   private static bool IsACollection(PropertyDescriptor descriptor)
      {
          bool isCollection = false;
  
          foreach (Type type in descriptor.PropertyType.GetInterfaces())
          {
              if (type.IsGenericType)
              {
                  if (type.GetGenericTypeDefinition() == typeof(ICollection&lt;&gt;))
                  {
                      isCollection = true;
                      break;
                  }
              }
              else
              {
                  if (type == typeof(ICollection))
                  {
                      isCollection = true;
                      break;
                  }
              }
          }
  
  
          return isCollection;
      }
  
      private static bool IsADto(PropertyDescriptor descriptor)
      {
          bool isDto = false;
  
          foreach (Type type in descriptor.PropertyType.GetInterfaces())
          {
              if (type == typeof(IDto))
              {
                  isDto = true;
                  break;
              }
          }          
          return isDto;
      }
  </code></pre>
  
  <p>However I am convinced there has to be a better way than this.  I have tried comparing in a normal fashion such as:</p>
  
  <pre><code>if(descriptor.PropertyType == typeof(ICollection&lt;&gt;))
  </code></pre>
  
  <p>However, this fails when using reflection yet when not using reflection it works fine.</p>
  
  <p>I don't want to iterate through the interfaces for every field of my entity.  Could someone shed some light on another method in which to do this?  Yes, I am prematurely optimizing, but it looks ugly too so please humor me.</p>
  
  <p>Caveats:</p>
  
  <ol>
  <li>It could or could not be generic, such as IList&lt;> or just ArrayList thus why I am looking for ICollection or ICollection&lt;>.  So I assume I should use IsGenericType in an if statement to know whether to test using ICollection&lt;> or not.</li>
  </ol>
  
  <p>Thanks in advance!</p>