What are differences between declaring a method in a base type \"virtual
\" and then overriding it in a child type using the \"override
\" keyword as
My version of explanation comes from using properties to help understand the differences.
override
is simple enough, right ? The underlying type overrides the parent's.
new
is perhaps the misleading (for me it was). With properties it's easier to understand:
public class Foo
{
public bool GetSomething => false;
}
public class Bar : Foo
{
public new bool GetSomething => true;
}
public static void Main(string[] args)
{
Foo foo = new Bar();
Console.WriteLine(foo.GetSomething);
Bar bar = new Bar();
Console.WriteLine(bar.GetSomething);
}
Using a debugger you can notice that Foo foo
has 2 GetSomething
properties, as it actually has 2 versions of the property, Foo
's and Bar
's, and to know which one to use, c# "picks" the property for the current type.
If you wanted to use the Bar's version, you would have used override or use Foo foo
instead.
Bar bar
has only 1, as it wants completely new behavior for GetSomething
.