Reputation: 61
What's the real life scenario where we will use new to provide new implementation for a virtual method in the derived class? C#
I know what it means technically. what I am looking for is a real life scenario where this will be needed.
We can always achieve the same by providing the override functionality. Why would we want to incorrect method been picked when methods call is made casted to base.
Upvotes: 6
Views: 2045
Reputation: 29
A virtual method can be redefined. The virtual keyword designates a method that is overridden in derived classes. We can add derived types without modifying the rest of the program. The runtime type of objects thus determines behavior.
Upvotes: 0
Reputation: 1503779
No, you can't achieve the same by overriding:
One example scenario:
At this point, you want all your existing code calling Bar.DoSomething to still call Bar.DoSomething, but all the code which calls Foo.DoSomething should still call that implementation - those callers may not even know about your method, and they may be in the third party assembly.
In the long term in that situation you would probably want to rename your method if you can (depending on how much control you have over your callers) but in the short term, making your method as new
achieves exactly the behaviour you want.
This sort of thing is sometimes known as the brittle base class problem. Eric Lippert has written about it reasonably extensively, including this post back in 2004.
Upvotes: 5
Reputation: 15577
No. You can't achieve the same.
// Define the base class
class Car
{
public virtual void DescribeCar()
{
System.Console.WriteLine("Four wheels and an engine.");
}
}
// Define the derived classes
class ConvertibleCar : Car
{
public new virtual void DescribeCar()
{
base.DescribeCar();
System.Console.WriteLine("A roof that opens up.");
}
}
class Minivan : Car
{
public override void DescribeCar()
{
base.DescribeCar();
System.Console.WriteLine("Carries seven people.");
}
}
Now, if you try to do this:
public static void TestCars2()
{
Car[] cars = new Car[3];
cars[0] = new Car();
cars[1] = new ConvertibleCar();
cars[2] = new Minivan();
}
The result will be:
Car object: YourApplication.Car
Four wheels and an engine.
----------
Car object: YourApplication.ConvertibleCar
Four wheels and an engine.
----------
Car object: YourApplication.Minivan
Four wheels and an engine.
Carries seven people.
----------
Override ALWAYS override while new ONLY does it when is used as its declared type (not base one).
You can see more here
Upvotes: 5