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?
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.