Confused about "override" vs. "new" in C#
Posted
by iTayb
on Stack Overflow
See other posts from Stack Overflow
or by iTayb
Published on 2010-06-01T20:00:11Z
Indexed on
2010/06/01
20:13 UTC
Read the original article
Hit count: 222
I'm having the following classes:
class Base
{
public virtual void Print()
{
Console.WriteLine("Base");
}
}
class Der1 : Base
{
public new virtual void Print()
{
Console.WriteLine("Der1");
}
}
class Der2 : Der1
{
public override void Print()
{
Console.WriteLine("Der2");
}
}
This is my main method:
Base b = new Der2();
Der1 d1 = new Der2();
Der2 d2 = new Der2();
b.Print();
d1.Print();
d2.Print();
The output is Base
, Der2
, Der2
.
As far as I know, Override won't let previous method to run, even if the pointer is pointing to them. So the first line should output Der2
as well. However Base
came out.
How is it possible? How the override didn't work there?
© Stack Overflow or respective owner