0

I'm using C#. I have two classes A and B. B inherits from A. They both have a Foo() method (which is virtual in A). Now, if I have

A b = new B();
int x = b.Foo();

then Foo() from A is called. But if Foo() in B has the 'new' keyword, then again the Foo() from the base class is called. Then, why would I use shadowing?

petko_stankoski
  • 10,459
  • 41
  • 127
  • 231

4 Answers4

3

The only case where I used method hiding is when I want to return a derived type in the derived class (the actual object being returned from both methods should be identical here). Of course this is only a hack around C#s lack of result type covariance.

CodesInChaos
  • 106,488
  • 23
  • 218
  • 262
  • Why would I use shadowing when the result is the same without it? – petko_stankoski Oct 23 '11 at 16:52
  • Because you can then use a more specific/derived type as your return type in your derived class. `object IEnumerator.Current` vs `T IEnumerator.Current` is something very similar. There you can get elements of type `T` if you know the correct `T`, and `object` if you don't. But (a well behaved implementation of) `Current` still returns the same object for both. – CodesInChaos Oct 23 '11 at 17:05
2

Knowing When to Use Override and New Keywords (C# Programming Guide)

Muhammad Hasan Khan
  • 34,648
  • 16
  • 88
  • 131
1

Using new means exactly that: don't override.

The only effect of new is to suppress the compiler warning about hiding a base-member. It will never cause a different method to be called.

H H
  • 263,252
  • 30
  • 330
  • 514
0

It's quite useful with polymorphism.

This post might be a good start.
Hasan Khan also posted a good one that I was going to mention (no need anymore).
This other post might be of help too.

Community
  • 1
  • 1
Anderson Matos
  • 3,132
  • 1
  • 23
  • 33
  • I know what's the difference between overriding and shadwing. I don't know why I would add the new keyword in the method, when the result is the same without it. – petko_stankoski Oct 23 '11 at 16:51
  • Than your question is wrong. It's not "Then, why would I use shadowing?" but "Why should I add the new keyword in the method when the result is the same without it?". – Anderson Matos Oct 26 '11 at 15:54
  • adding the new keyword in the method = shadowing => why would I use shadowing? = Why should I add the new keyword in the method – petko_stankoski Oct 27 '11 at 10:14
  • Sorry, but not. Shadowing is a concept. Why use it is a question for the porpouse of shadowing itself and why it is or isn't useful. Now, if you need to know about the usage of an specific keyword (and if it has any effect at all), ask for that. Plain simple. Avoids misunderstandings. Just that. No need to hate me, just that there is no way for everyone here to find your intention on the question. It *needs* to be explicit. – Anderson Matos Oct 31 '11 at 16:50