Reputation: 2754
What are Advantages and Disadvantages of Method or property hiding in C#.
Upvotes: 1
Views: 2346
Reputation: 13286
I don't think there is any advantage in property hiding. You have to do so when the property or method in the base class is not defined as virtual or abstract, or when your method differs from the base class method by return type. The disadvantage is clear. The base class method still exists and there is no way you can force the class user to use your method:
Derived d = new Derived();
((Base)d).DoSomething() // this will call the base method
Upvotes: 2
Reputation: 46366
Method hiding by using the new
keyword has the effect of breaking polymorphism. If you're using method hiding you cannot invoke the hidden behavior when accessing the method via it's base type or interface.
void Main()
{
var nohiding = new NoHiding();
var hiding = new Hiding();
nohiding.DoSomething(); // "Overridden Method"
hiding.DoSomething(); // "Hidden Method"
var nohidingAsBase = (Base) nohiding;
var hidingAsBase = (Base) hiding;
nohidingAsBase.DoSomething(); // "Overridden Method"
hidingAsBase.DoSomething(); // "Base Method"
}
public class Base
{
public virtual void DoSomething()
{
Console.WriteLine("Base Method");
}
}
public class NoHiding : Base
{
public override void DoSomething()
{
Console.WriteLine("Overriden Method");
}
}
public class Hiding : Base
{
new public void DoSomething()
{
Console.WriteLine("Hidden Method");
}
}
As to your question of advantages/disadvantages there isn't a clear list. Method hiding is used very little, and I would say it's a bit like the goto
keyword. Generally it's not something you should use, but it can be very helpful under specific circumstances.
Upvotes: 3