Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

method hiding in c# with a valid example. why is it implemented in the framework? what is the Real world advantage?

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?

like image 572
vijaysylvester Avatar asked Jul 28 '09 12:07

vijaysylvester


1 Answers

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.

like image 152
jeroenh Avatar answered Sep 23 '22 00:09

jeroenh