Generics IAbstract<T> inherits from IAbstract

I am trying to achieve something like this:

interface IAbstract
{
    string A { get; }
    object B { get; }
}

interface IAbstract<T> : IAbstract
{
    T B { get; }
}

class RealThing<T> : IAbstract<T>
{
    public string A { get; private set; }
    public T B { get; private set; }
}

So I can do something like this:

RealThing<string> rt = new RealThing<string>();
IAbstract ia = rt;
IAbstract<string> ias = rt;
object o = ia.B;
string s = ias.B;

Is this possible?

Jon Skeet
people
quotationmark

Very nearly. Three things:

  • You should use new in IAbstract<T> to indicate that you know you're hiding an existing member:

    new T B { get; }
    

    But even without that, you'll still only get a warning.

  • You need to implement the IAbstract.B within RealThing, which you should almost certainly do using explicit interface implementation, delegating to the strongly-typed member:

    object IAbstract.B { get { return B; } }
    
  • Within your test code, you need to specify a type argument for RealThing:

    RealThing<string> rt = new RealThing<string>();
    

This is fine, and even a reasonably common pattern for times where you want to be able to get a non-generic form of an interface.

people

See more on this question at Stackoverflow