I've got a question concerning polymorphic methods. I've got two classes: the base class with the non-virtual method Foo( )
which calls its virtual method Foo (int i)
(like this: Foo() {Foo(1);})
and the derived class which overrides method Foo(int i)
.
If I call Foo()
method of an instance of the derived class the walkthrough is as the following: base Foo() -> override Foo(int i)
. But if I change override method to new the walkthrough is as the following: base Foo -> base Foo(int i)
. It doesn't even get to the new Foo(int i)
method. Please, explain the sequence of those methods and why it is the way it is.
using System;
class Program
{
sealed void Main()
{
DerivedClass d = new DerivedClass();
//Goes to BaseClass Foo() method
//then goes to Derived Foo(int i ) method
d.Foo();
}
}
class BaseClass
{
public void Foo() { Foo(1); }
public virtual void Foo(int i) { // do something;
}
}
class DerivedClass : BaseClass
{
public override void Foo(int i) { //Do something
}
}
//////////////////////////////////////////////////////////////////////
using System;
class Program
{
sealed void Main()
{
DerivedClass d = new DerivedClass();
//Goes to BaseClass Foo() method
//then goes to base Foo(int i) method
//never gets to Foo(int i) of the derived class
d.Foo();
}
}
class BaseClass
{
public void Foo() { Foo(1); }
public virtual void Foo(int i) { // do something;
}
}
class DerivedClass : BaseClass
{
public new void Foo(int i) { //Do something
}
}
(When using new
.)
It doesn't even get to the new Foo(int i) method.
Yes it does - but it executes the BaseClass
implementation of Foo(int)
because it's not overridden in the derived class. That's the whole point of new
- it's saying, "I'm not overriding a base class method - I'm a whole new method." If you want to override the base class method, use override
. The clue is in the keyword :)
So for example, when using new
:
BaseClass x = new DerivedClass();
x.Foo(1); // Calls BaseClass.Foo(int)
DerivedClass y = new DerivedClass();
y.Foo(1); // Calls DerivedClass.Foo(int)
But when using override
:
BaseClass x = new DerivedClass();
x.Foo(1); // Calls DerivedClass.Foo(int) // Due to overriding
DerivedClass y = new DerivedClass();
y.Foo(1); // Calls DerivedClass.Foo(int)
See more on this question at Stackoverflow