Echilon
Echilon

Reputation: 10264

Inheritance and Overriding Methods/Properties

If I have two classes, one which inherits from the other and I use the same method/property name in both, how can I make that method call the subclass regardless of whether the current object has been cast back to it's base class.

For example (extraneous parts omitted):

public class MyBase {
    public int GetNumber() {
        return 1;
    }
}

public class MyDerived : MyBase {
    public new int GetNumber() {
        return 20;
    }
}

MyDervied someVar = new MyDerived();
int derivedVar = someVar.GetNumber(); // 20

MyBase baseVar = (MyBase)someVar;
int baseVar = baseVar.GetNumber(); // 1

My instinct would be to use override instead of new for the derived class, but I get a "no member found to override".

Upvotes: 1

Views: 990

Answers (2)

Joren
Joren

Reputation: 14746

Dahlbyk is right. new is useful if you want to derive a class and add a new member, but coincidentally the class already has a member with the same name. It's for adding a new member, not for changing the behaviour of an existing one.

class A
{
    public void Foo()
    {
        Console.WriteLine("A.Foo()");
    }
}

class B : A
{
    public new void Foo()
    {
        Console.WriteLine("B.Foo()");
    }
}

...

A x = new A();
x.Foo(); // prints "A.Foo()"

B y = new B();   
y.Foo(); // prints "B.Foo()"

A z = y;
z.Foo(); // prints "A.Foo()", not "B.Foo()"!

Note the difference in behaviour when compared to an overridden method, which would print "B.Foo()" in the latter case.

Upvotes: 1

dahlbyk
dahlbyk

Reputation: 77620

Your base method needs to be marked virtual before you can override.

public class MyBase {
    public virtual int GetNumber() {
        return 1;
    }
}

public class MyDerived : MyBase {
    public override int GetNumber() {
        return 20;
    }
}

Upvotes: 7

Related Questions