Reputation: 2444
I have several classes all implementing an interface IBar
. Those classes are BarA
, BarB
, BarC
.
I also have a base class Foo
:
abstract class Foo
{
void Do(IBar bar)
{
Handle((dynamic)bar);
}
void Handle(IBar bar)
{
Console.Out.WriteLine("Fallback Scenario");
}
}
I want a child class FooChild
like follows:
class FooChild : Foo
{
void Handle(BarA bar) {
Console.Out.WriteLine("Handling BarA");
}
void Handle(BarB bar) {
Console.Out.WriteLine("Handling Bar");
}
}
No I want to do the following, but I don't get the result I expect
var foo = new FooChild();
foo.Handle(new BarA()); // expected: Handling BarA, actual: Fallback Scenario
foo.Handle(new BarB()); // expected: Handling BarB, actual: Fallback Scenario
foo.Handle(new BarC()); // expected: Fallback Scenario, actual: Fallback Scenario
I can solve it by moving the Do(IBar bar)
method to the FooChild
class, but I don't want to do that. I might have 10 Foo
childs and don't want to repeat that code. Is there a solution for this?
Upvotes: 4
Views: 379
Reputation: 1500525
I think you want this:
void Do(IBar bar)
{
dynamic dynamicThis = this;
dynamicThis.Handle((dynamic) bar);
}
That way the method will be found against the actual type of this
. Otherwise, the compiler remembers that the method was called from Foo
, and only treats the argument dynamically, finding methods which would have been available from Foo
with the actual type of bar
. You want methods which would have been available from the actual type of this
, as well as using the actual type of bar
(via the cast to dynamic
).
(You'll need to make the Handle
methods public though.)
Upvotes: 4