MrRobot9
MrRobot9

Reputation: 2684

Method from base class is called always

I have a base class and a derived class

public interface IDispatch {
    void DoSomething();
}

public class Foo : IDispatch {
    void DoSomething() {

    }
}

public class Bar : Foo {
     void DoSomething() {

    }
}

I have a function, based on the condition, I'm referencing it.

  Foo randomfunc(Foo f){
    if(...){
         f = new Foo();
    }else{
         f = new Bar();
    }
   f.dosomething(); // this works fine
   return f;

    }

But in the method call

Foo qwe;
qwe = randomfunc(f);
qwe.doSomething(); //it calls doSomething() from Foo() even though it references Bar

Where am I going wrong?

Upvotes: 1

Views: 99

Answers (1)

Rob
Rob

Reputation: 27357

You're hiding the methods, not overriding them. In fact, you'll get a warning for the code you've written (assuming you fix the compiler error since you're implementing the interface with private methods).

This:

public class Bar : Foo
{
    public void DoSomething()
    {

    }
}

Is equivalent to this:

public class Bar : Foo
{
    public new void DoSomething()
    {

    }
}

However, the latter will prevent a warning, as it's telling the compiler "I know what I'm doing".

With method hiding, it means that Bar's implementation will only be invoked if the object you invoke it on is cast as Bar. That's the behaviour you're experiencing here. What you actually want to do is override the method, not hide it. For example:

public class Foo : IDispatch
{
    public virtual void DoSomething()
    {

    }
}

public class Bar : Foo
{
    public override void DoSomething()
    {

    }
}

Upvotes: 4

Related Questions