Possible Duplicate:
C# keyword usage virtual+override vs. new
Difference between new and override?
So I've been working on a project and decided to do some reading about the difference between the new
and override
keywords in C#.
From what I saw, it seems that using the new
keyword functionality is a great way to create bugs in the code. Apart from that I don't really see when it would actually make sense to use it.
More out of curiosity than anything, is there any pattern where the new
keyword is the right way to go?
The new
keyword is the right way to go when you want to hide a base implementation and you don't care that you won't be able to call your method when treating your object polymorphically.
Let me clarify. Consider the following:
public class Base
{
public void DoSomething()
{
Console.WriteLine("Base");
}
}
public class Child : Base
{
public new void DoSomething()
{
Console.WriteLine("Child");
}
}
From time to time, it is beneficial to hide the base class' functionality in the child hence the use of the new
keyword. The problem is that some developers do this blindly which will lead to the following side effect (hence the 'bugs' you mention):
Base instance = new Child();
instance.DoSomething(); // may expect "Child" but writes "Base"