C# - Keyword usage virtual+override vs. new
c#, member-hiding, method-hiding, overriding, syntax
Solution
The "new" keyword doesn't override, it signifies a new method that has nothing to do with the base class method.
public class Foo
{
public bool DoSomething() { return false; }
}
public class Bar : Foo
{
public new bool DoSomething() { return true; }
}
public class Test
{
public static void Main ()
{
Foo test = new Bar ();
Console.WriteLine (test.DoSomething ());
}
}
This prints false, if you used override it would have printed true.
(Base code taken from Joseph Daigle)
So, if you are doing real polymorphism you SHOULD ALWAYS OVERRIDE. The only place where you need to use "new" is when the method is not related in any way to the base class version.
Problem
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?