Can anyone explain the actual use of method hiding in C# with a valid example ?
If the method is defined using the new
keyword in the derived class, then it cannot be overridden. Then it is the same as creating a fresh method (other than the one mentioned in the base class) with a different name.
Is there any specific reason to use the new
keyword?
One use I sometimes have for the new keyword is for 'poor mans property covariance' in a parallell inheritance tree. Consider this example:
public interface IDependency
{
}
public interface ConcreteDependency1 : IDependency
{
}
public class Base
{
protected Base(IDependency dependency)
{
MyDependency = dependency;
}
protected IDependency MyDependency {get; private set;}
}
public class Derived1 : Base // Derived1 depends on ConcreteDependency1
{
public Derived1(ConcreteDependency1 dependency) : base(dependency) {}
// the new keyword allows to define a property in the derived class
// that casts the base type to the correct concrete type
private new ConcreteDependency1 MyDependency {get {return (ConcreteDependency1)base.MyDependency;}}
}
The inheritance tree Derived1 : Base has a 'parallell dependency' on ConcreteDependency1 : IDependency'. In the derived class, I know that MyDependency is of type ConcreteDependency1, therefore I can hide the property getter from the base class using the new keyword.
EDIT: see also this blog post by Eric Lippert for a good explanation of the new keyword.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With