Just curious if there is a solution for this without making the base class method virtual and the derived method marked override:
I want it to jump into the derived method, set the property to true (for testing purposes, almost like this is a mock), but it’s jumping into the base class. The only solution is to make the base virtual, I thought I could mark it new in the derived and that would work.
public class SomeClass
{
private readonly IFoo _foo;
public SomeClass(IFoo foo)
{
_foo = foo;
}
public void DoSomething()
{
_foo.DoFoo();
}
}
public interface IFoo
{
void DoFoo();
}
public class Foo : IFoo
{
public void DoFoo()
{
}
}
public class Foo2 : Foo
{
public bool DoFooWasCalled { get; set; }
public new void DoFoo()
{
DoFooWasCalled = true;
base.DoFoo();
}
}
Here’s the test that is failing:
[TestFixture]
public class TestingCSInheritance
{
[Test]
public void TestMethod()
{
var foo = new Foo2();
var someClass = new SomeClass(foo);
someClass.DoSomething();
foo.DoFooWasCalled.ShouldBe(true);
}
}
My guess is that because I’m using dependency injection with an interface it’s using the base class, but I’m not sure why.
No. If you create a new method, only code which knows about the expression with a compile-time type of
Foo2will callFoo2.DoSomething.Even though
TestMethodknows aboutfooas aFoo2,SomeClass.DoSomethingonly knows about it asIFoo, so it’s just using theIFooimplementation.Foo2.DoSomethingis not an implementation ofIFoo.You want polymorphism, but you’ve effectively discarded it by not using a virtual method.
The only other option is to reimplement
IFooin Foo2, which is the solution described by Sergey. Note that this ends up with some pretty confusing code. Method hiding of any kind almost always does. Fundamentally, if you want the effect of a virtual method, you should use a virtual method…Alternatively, it would be cleaner if you used composition instead of inheritance:
This delegates the call to
DoSomethinginstead of trying to juggle an inheritance hierarchy.