title: Creating a generic interface in C#
body: <p>I know that the title may be confusing (or even misleading), but I'm planning to create an interface which is generic, and it should implement a method involving a generic parameter.</p>
  
  <p>When implemented in class <code>AFirst</code>, it should have a method <code>MyMethod&lt;A&gt;()</code> that returns the type A, and when implemented in class <code>BFirst</code>, it should have a method <code>MyMethod&lt;B&gt;()</code> that returns type B. I need this functionality as there is an inheritance relationship between A and B (and MANY others) and I need a generic method that I can call with any of the base classes.</p>
  
  <p>If it was confusing, have a look at what I want to do:</p>
  
  <p>Consider B derives from A.
  Consider AFirst and BFirst implement <code>IMyInterface&lt;A&gt;</code> and <code>IMyInterface&lt;B&gt;</code> respectively:</p>
  
  <pre><code>BFirst mySecondObj = new BFirst();
  A myA = BFirst.MyMethod&lt;A&gt;();
  B myB = BFirst.MyMethod&lt;B&gt;();
  </code></pre>
  
  <p>I need access to the <code>MyMethod</code> templates for the base classes to, so when I instantiate the <code>BFirst</code> instance, I can call either <code>MyMethod</code> for <code>A</code> or <code>B</code>. I'm building a template system and think these <code>AFirst</code> and <code>BFirst</code> are the templates, and <code>MyMethod</code> acts like a factory method. I will have a big hierarchy, and the project needs to be extensible by deriving even more classes from my base class <code>A</code>, so I can't just create seperate interfaces or methods for each of them.</p>
  
  <p>I tried this:</p>
  
  <pre><code>interface IMyInterface&lt;T&gt; where T : A
  {
      T GetNewInstance&lt;T&gt;();
  }
  </code></pre>
  
  <p>and I tried to implement this way, but I'm getting it as created like this when I click implement:</p>
  
  <pre><code>class AFirst : IMyInterface&lt;A&gt;
  {
      public T GetNewInstance&lt;T&gt;()
      {
          throw new NotImplementedException();
      }
  }
  </code></pre>
  
  <p>Didn't make sense to me in the way that I've specified the T type to be <code>A</code>, but it still implements as T. For example, it will go like this (below is how I want it to happen)</p>
  
  <pre><code>class AFirst : IMyInterface&lt;A&gt;
  {
      public A GetNewInstance&lt;A&gt;()
      {
          throw new NotImplementedException();
      }
  }
  
  class BFirst : AFirst, IMyInterface&lt;B&gt;
  {
      public B GetNewInstance&lt;B&gt;()
      {
          throw new NotImplementedException();
      }
  }
  </code></pre>
  
  <p>and from outer code, call the sample as in the beginning of my question:</p>
  
  <pre><code>BFirst myBFirst = new BFirst();
  A a = BFirst.GetNewInstance&lt;A&gt;(); //calls AFirst's method and returns A
  B b = BFirst.GetNewInstance&lt;B&gt;(); //calls BFirst's method and returns B
  </code></pre>
  
  <p>How is this possible?
  Thanks,
  Can.</p>