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 d
One slightly obscure scenario where method hiding would be appropriate, but for a lack of any clean idiomatic way of expressing it, is in circumstances where a base class exposes a protected member to an inheritable descendant, but that descendant knows that there is no way any further derived classes could use that member without breaking things. A prime example of a method which many classes should hide (but very few do) is MemberwiseClone()
. In many cases, if a class has a private
member which expects to be the only extant reference to a mutable object, there is no possible means by which a derived class could ever use MemberwiseClone()
correctly.
Note that hiding of protected members does not constitute a violation of the LSP. Conformance with the LSP requires that in places where code might be expecting reference to a base-class object but receives a reference to a derived-class object, the latter object should work as would the base-class one. Protected members, however, are outside the scope of the LSP, since every type knows its base type absolutely. If Bar
and Boz
both derive from Foo
, and Boz
hides a protected member that Bar
requires, the fact that Boz
hides the member won't affect Bar
, because Bar
's base-type instance can't possibly be a Boz
or anything other than Foo
. No substitution is possible, and hence substitutability is irrelevant.