title: C#: cast to generic interface with base type
body: <p>Here's the code:</p>
  
  <pre><code>public interface IValidator&lt;T&gt;
  {
     bool IsValid(T obj);
  }
  
  public class OrderValidator: IValidator&lt;Order&gt;
  {
    // ...
  }
  
  public class BaseEntity
  {
  }
  
  public class Order: BaseEntity
  {
  }
  </code></pre>
  
  <p>The problem is that I can't do:</p>
  
  <pre><code>var validator = new OrderValidator();
  // this line throws because type can't be converted
  var baseValidator = (IValidator&lt;BaseEntity&gt;)validator;
  // all this is because I need a list with IValidator&lt;Order&gt;, IValidator&lt;BaseOrder&gt;, etc.
  IList&lt;IValidator&lt;BaseEntity&gt;&gt; allValidators = ... 
  </code></pre>
  
  <p>How do I get and store a list of all implementations of IValidator&lt;T&gt; for base T - say, BaseEntity? Currently I do non-generic IValidator that accepts "object obj" but it is not good and not type-safe.</p>
  
  <p>The funny stuff is that C# <strong>allows</strong> to compile:</p>
  
  <pre><code>var test = (IValidator&lt;BaseEntity&gt;)new OrderValidator();
  </code></pre>
  
  <p>but fails at runtime with</p>
  
  <pre><code>   Unable to cast object of type 'OrderValidator' to type 'IValidator`1[Orders.Core.BaseEntity]'
  </code></pre>
  
  <p>This is the same exception that Windsor gives me (I tried both Windsor and manual types lookup, this issue is really not related to this, only to the interfaces casting).</p>
  
  <p>Thanks to Heinzi, I see now why I can't cast - because IValidator for Order expects Order as generic type. But how do I return a list of IValidator for different types? The reason is that the BaseEntity takes its real type and gathers all validators - for all types from GetType() to the object. I'd really like to have a generic GetValidators() and then operate on it.</p>