C# Generics and polymorphism: an oxymoron?

c#, generics, polymorphism

Solution

As far as I can see, consuming code doesn't need specifics of generic class (i.e., it doesn't depends on what `T` is). So, why don't you introduce interface that `SomeClass<T>` will implement, and use instance of this interface.

E.g.:

public interface ISome
{
    void SomeMethod();
}

public class SomeClass<T>: ISome
{
    public virtual void SomeMethod(){ }
}

public void DoSomethingClienty()
{
    Factory factory = new Factory();
    ISome someInstance = factory.Create();

    someInstance.SomeMethod();
}

Now, subclasses of `SomeClass<T>` can operate differently on different `T`s, but consuming code won't change.

Problem

I just want to confirm what I've understood about Generics in C#. This has come up in a couple code bases I've worked in where a generic base class is used to create type-safe derived instances. A very simple example of what I'm talking about, ``` public class SomeClass<T> { public virtual void SomeMethod(){ } } public class DeriveFrom :SomeClass<string> { public override void SomeMethod() { base.SomeMethod(); } } ``` The problem comes up when I then want to use derived instances in a polymorphic way. ``` public class ClientCode { public void DoSomethingClienty() { Factory factory = new Factory(); //Doesn't compile because SomeClass needs a type parameter! SomeClass someInstance = factory.Create(); someInstance.SomeMethod(); } } ``` It seems that once you introduce a Generic into an inheritance hierarchy or interface, you can no longer use that family of classes in a polymorphic way except perhaps internal to itself. Is that true?

Original source