Alex Rivera | Logout

Valid applications of member hiding with the new keyword in c#

Asked 2010-05-06T20:53:00.523
21

I've been using c# since version 1, and have never seen a worthwhile use of member hiding. Do you know of any?

c#
Edit
Report

2 Answers

17

Scenario #1:

Imagine you are designing the runtime library for .NET 2.0. You now have generics at your disposal. You have an interface:

interface IEnumerable 
{
    IEnumerator GetEnumerator();
}

You wish to make a new interface

interface IEnumerable<T> 
{
    IEnumerator<T> GetEnumerator();
}

You now have three choices.

1) Make the generic version unrelated to the non-generic version.

2) Make the generic version extend the non-generic version. You now have two methods that differ only in return type. Change the name of GetEnumerator in the new type to GetEnumerator2(). Because that's hot. Everyone loves a good "2" method.

3) Make the generic version extend the non-generic version. Make the new and improved method hide the existing method so that its there if you need it, but hidden by default.

These are all bad choices. Which would you choose? We chose (3). Good thing that it was an option; without hiding, that option would not have been available.

Now, you might argue that this particular example of hiding was not 'worthwhile'; if that's so, what would you have done instead?

Method hiding makes it possible to expose improved interfaces without causing breakages when there are improvements to the type system.

Scenario #2:

You work at FrobCo. You produce a class Frobber that extends Blobber, which is supplied to you by the good people at BlobCo.

BlobCo has neglected to put a Frobozzle() method on Blobber, but your customers love to frobozzle frobbers, so you add a method Frobozzle() to derived class Frobber.

BlobCo realizes that their customers want to Frobozzle blobbers, so they add a non-virtual method Frobozzle() to Blobber, the base class.

Now what do you do, FrobCo employee?

1) Remove the Frobozzle method on Frobber, thereby breaking your customers who

answered 2010-05-06T22:19:45.010
2

Generally it's considered bad practice to reject an inherited member. The only time I've used it is in generated code where the new member provided a more specific type in the same class hierarchy. Same goes for explicit interface implementations.

answered 2010-05-06T21:14:54.100

Your Answer