Hiding inherited method

G

Guest

I was trying to break some polymorphism, expecting it not to work, but I'm a
curious sort.

I was seeing what happens when a derived class tries to hide an inherited
method with a private new method, expecting an error or warning; I got
neither with the result that the inherited method does _not_ get hidden (i.e.
not possibe to break polymorphism/inheritance this way, yay!)

My question then is, why is there no warning that the code may not work the
way the writer expects? Is it simply because the _new_ keyword turns it off?
Without the _new_ keyword, the warning about hiding fires, but this is a case
where no hiding will happen anyway, because the private method _does_not_
hide the inherited method.
 
J

Jon Skeet [C# MVP]

PIEBALD said:
I was trying to break some polymorphism, expecting it not to work, but I'm a
curious sort.

I was seeing what happens when a derived class tries to hide an inherited
method with a private new method, expecting an error or warning; I got
neither with the result that the inherited method does _not_ get hidden (i.e.
not possibe to break polymorphism/inheritance this way, yay!)

My question then is, why is there no warning that the code may not work the
way the writer expects? Is it simply because the _new_ keyword turns it off?
Without the _new_ keyword, the warning about hiding fires, but this is a case
where no hiding will happen anyway, because the private method _does_not_
hide the inherited method.

Well, it hides it within that class - it just doesn't hide it for other
users of the class.
 
B

Bob Milton

And, by casting the derived object to the base class, I can even call
the "hidden" method!
Bob
 
J

Jon Skeet [C# MVP]

Bob Milton said:
And, by casting the derived object to the base class, I can even call
the "hidden" method!

Absolutely - but that's always true with "hiding", as anything else
would break Liskov's Substitution Principle.
 
B

Bob Milton

True. But it still amazes me how many people want to be able to
eliminate a public function in the base class (which in essence you can't
really do).
Bob
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top