-4

I am learning C#, but I do not understand what's the use of method hiding? I searched the web but I still don't understand exactly how it works. Can anyone explain how it works?

Sayse
  • 42,633
  • 14
  • 77
  • 146
bAthi
  • 341
  • 4
  • 20
  • 1
    do you mean: "How it works" or "why should you do that" ? – Cadburry Jun 08 '15 at 08:10
  • I am asking any use is there or not – bAthi Jun 08 '15 at 08:11
  • ok can you send me any reference links for that? – bAthi Jun 08 '15 at 08:13
  • 1
    Relateds: [Overriding vs method hiding](http://stackoverflow.com/questions/856449/overloading-overriding-and-hiding) and [Overloading,Overriding and Hiding?](http://stackoverflow.com/questions/856449/overloading-overriding-and-hiding). Note: these were pretty much top results on google for "method hiding" – Sayse Jun 08 '15 at 08:13
  • http://www.akadia.com/services/dotnet_polymorphism.html – Mirza Danish Baig Jun 08 '15 at 08:27

2 Answers2

1

Method hiding is a technique used to replace a non-virtual method of a base class with new functionality in the child class. It has some nasty behaviour that can easily catch people out. To explain by way of an example:

class BaseClass 
{
    public void Foo() 
    {
        Console.WriteLine("BaseClass");
    }
}

class ChildClass : BaseClass 
{
    public new void Foo()
    {
        Console.WriteLine("ChildClass");
    }
}

ChildClass obj1 = new ChildClass();
BaseClass obj2 = obj1;
obj1.Foo(); // Prints "ChildClass"
obj2.Foo(); // Prints "BaseClass"

If Foo had been declared virtual, new would not be needed and both obj1.Foo() and obj2.Foo() would have printed ChildClass in the example above.

The only other thing you need to know about it is that these days using inheritance is generally frowned upon (do a search of either "inheritance is evil" or "composition vs inheritance" for reams of info on why this is). You therefore shouldn't need to worry about method hiding (unless someone inflicts it upon you with their old and/or misguided code).

David Arno
  • 42,717
  • 16
  • 86
  • 131
0

Method hiding refers to Information Hiding which is a very basic pattern generally used in programming. Basically you usually want to achieve a clean separation of your components and implementation details from interfaces.

  • 1
    I don't think he's referring to encapsulation, I think he's talking about [this](https://msdn.microsoft.com/en-us/library/435f1dw2.aspx). – dcastro Jun 08 '15 at 08:24