C# - Keyword usage virtual+override vs. new

i3ensays picture i3ensays · Oct 2, 2008 · Viewed 65.2k times · Source

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 opposed to simply using the "new" keyword when declaring the matching method in the child type?

Answer

Orion Edwards picture Orion Edwards · Oct 2, 2008

I always find things like this more easily understood with pictures:

Again, taking joseph daigle's code,

public class Foo
{
     public /*virtual*/ bool DoSomething() { return false; }
}

public class Bar : Foo
{
     public /*override or new*/ bool DoSomething() { return true; }
}

If you then call the code like this:

Foo a = new Bar();
a.DoSomething();

NOTE: The important thing is that our object is actually a Bar, but we are storing it in a variable of type Foo (this is similar to casting it)

Then the result will be as follows, depending on whether you used virtual/override or new when declaring your classes.

Virtual/Override explanation image