Search code examples
c#inheritanceoverridingexplicit-interface

How to add new member and override abstract one at the same time?


Let's say you have interface IFoo and some member Member. The class which implements it is capable of implementing the member coming from interface and at the same time adding "new" member with exactly the same name.

It is really great. Now I would like to pull something similar but not coming from interface but from abstract class. I would expect similar behavior as with interface -- having instance of abstract class, the original Member would be seen, having instance of derived class the "new" member would be seen and original would be hidden.

I have something like this in mind:

abstract class AFoo
(
  public abstract string Member { get; }
}

class Foo : AFoo
{
  public override string Member { get; } // this is the one coming from AFoo

  public new int Member { get; } // does not work (try 1)
  string AFoo.Member { get; } // works only with interfaces (try 2)
}

Is there any mechanism to allow this?

Update: there are 2 members in Foo, I just wrote two tries. The usage would be same as with interface:

var foo = new Foo();
AFoo afoo = foo;
foo.Member; // gets int
afoo.Member; // gets string

Solution

  • Implement an intermediate class (InterFoo) that inherits the abstract class and that implements the required member:

    class InterFoo : AFoo
    {
        public override string Member { get; } 
    }
    

    Then have your class inherit from that intermediate class and have it shadow the base class version:

    class Foo : InterFoo
    {
        public new int Member { get; }
    }
    

    That Should work.