Search code examples
c#genericssuperclass

generic class with superclass


class Program
{
    static void Main(string[] args)
    {
        //GrandFather gf = new Son();
        IGF<Father> igf = new MyClass();
    }
}
public class Father
{

}
public class Son : Father
{
}
public class MyClass : IGF<Son>
{
    public void Method()
    {
        //DoSomething
    }
}
public interface IGF<T> where T : Father
{
    void Method();
}

Hello everyone,I meet a question when I using generic class with superclass. Can anyone tell me that why line 6 is wrong ,as when we using list,we always say that IList ss=new List();


Solution

  • If you're using C# 4.0, you can add the out keyword to the IGF implementation to make it a covariant interface. This allows you to have a generic with a base class (here Father) and have it point to an instance of that same interface with a derived generic type (Son).