tags:

views:

95

answers:

2

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".

+6  A: 

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;
    }
}
dahlbyk
+1  A: 

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 = b;
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.

Joren
Thanks. Perhaps I should have posted a specific example. I'm trying to use the same class in WPF and ASP.NET. WPF makes use of INotifyPropertyChanged, so I'm actually trying to change the return type of the base from List<string> to ObservableCollection<string>.
Echilon