C# – Keyword usage virtual+override vs. new

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

Leave a Comment