title: C# Generics and Generic Constraints
body: <p>I'm writing a generic abstract class A with type parameter T that I intend to derive with class B.</p>
  
  <p>A has a data member, mX, an instance of class C, with a generic function. This generic function, GetAllOfType(), has one type parameter, T. This type parameter is constrained to a third class, D. GetAllOfType() searches through a container of instances of D, which includes instances of D's derived classes, and returns the subset that are of the type T (hence the constraint to D).</p>
  
  <p>Class D itself does not have a particular data member, int mY, but some derived classes of D do, such as E and F. </p>
  
  <pre><code>public class D
  {
  }
  
  public class E : D
  {
      public int mY;
  }
  
  public class F : D
  {
      public int mY;
  }
  
  public class C
  {
      public T[] GetAllOfType&lt;T&gt;() where T : D
      { ... }
  }
  
  public class A&lt;T&gt;
  {
      private C mX;
      ...
  }
  
  public class B : A&lt;E&gt;
  {
      ...
  }
  </code></pre>
  
  <p>So here's where my problem starts:</p>
  
  <p>The parameter type that class B uses to inherit and implement class A is a derived class of D. I am attempting to write a function Foo in class A that enumerates through GetAllOfType() and accesses member mY of type E, F, or any other member that has a mY.</p>
  
  <pre><code>public class A&lt;T&gt;
  {
      private C mX;
  
      protected Foo()
      {
          foreach (var c in mX.GetAllOfType&lt;T&gt;())
          {
              c.mY = 0;
          }
      }
  }
  
  public class B : A&lt;E&gt;
  {
      public Bar()
      {
          Foo();
      }
  }
  </code></pre>
  
  <p>The problem, though, is that GetAllOfType() is constrained, and I am getting an error for not constraining class A as well.</p>
  
  <p>I've tried constraining A as such:</p>
  
  <pre><code>public class A&lt;T&gt; where T : D
  </code></pre>
  
  <p>But I'm getting a compile time error along the lines of:</p>
  
  <blockquote>
    <p>Type <code>T' does not contain a definition for</code>mY' and no extension method <code>mY' of type</code>T' could be found (are you missing a using directive or an assembly reference?)</p>
  </blockquote>
  
  <p>I have also tried to constrain to multiple derived classes:</p>
  
  <pre><code>public class A&lt;T&gt; where T : E, F
  </code></pre>
  
  <p>But I'm getting an error as well along the lines of:</p>
  
  <blockquote>
    <p>The class type constraint 'F' must be listed before any other constraints. Consider moving type constraint to the beginning of the constraint list</p>
  </blockquote>
  
  <p>I've tried switching them:</p>
  
  <pre><code>public class A&lt;T&gt; where T : F, E
  </code></pre>
  
  <p>Likewise, the result is the same error, but with F switched for E.</p>
  
  <p>Is what I am attempting possible? What am I doing wrong?</p>
  
  <p>Again, I can not change anything about classes C, D, E, and F.</p>