What if I don't heed the warning "hides inherited member. To make the current member override that implementation...."
Asked Answered
P

3

45

This is maybe a fine point, but it concerns the warning that the compiler issues if you do something like:

class A
{
    public virtual void F() { }
}
class B : A
{
    public void F() { }
}

Then you get the warning:

'EomApp1.B.F()' hides inherited member 'EomApp1.A.F()'.
To make the current member override that implementation, add the override keyword. Otherwise use the new keyword.

image of error message

QUESTION: What is the warning actually warning me will happen if I do nothing about it? Will my program function differently if I add the 'new' keyword vs. if I do not?

(Note: I know I could test this easily enough but I figured it was worth asking here)

Peaceful answered 9/5, 2011 at 5:54 Comment(0)
T
32

It will not do anything but the method you have there F() is also not polymorphic. It becomes very easy to make mistake in code if you started to use base class reference hence you are warned. Of course it can be what you want, hence the new keyword just make it more explicit

E.g.

B b1 = new B();
b1.F(); // will call B.F()

A b2 = new B();
b2.F(); // will call A.F()

Now, if you add class C with new, it will behave the same as B. If you add class D with override, then F becomes polymorphic:

class C : A
{
    public new void F() { }
}

class D : A
{
    public override void F() { }
}

// Later

C c1 = new C();
c1.F(); // will call C.F()

A c2 = new C();
c2.F(); // will call A.F()

D d1 = new D();
d1.F(); // will call D.F()

A d2 = new D();
d2.F(); // will call D.F()

See this fiddle.

Trubow answered 9/5, 2011 at 6:19 Comment(1)
Try it on VS, but I believe it will call A.F()Trubow
I
28

No, the default behaviour is exactly the same as if you use new, other than whether the warning is given. In my experience you more often actually want to specify override instead of new, as it's usually just a case of forgetting to explicitly override.

If you really do want a completely separate method, and if you've got the option of using a different name instead, I'd take that approach. Having one method hiding another usually reduces readability significantly IMO. It's not too bad if the purpose is to just give a more specific return type (and you make sure the more weakly typed method returns the same value), but that's a pretty rare case.

Inclinable answered 9/5, 2011 at 6:7 Comment(0)
A
0

This is just warning. Code will work. In some circumstance, this warning can lead to some problem.

use new keyword with the method which you are calling from the base class.

class A
{
    public virtual void F() { }
}
class B : A
{
   new public void F() { }
}

Reference

https://msdn.microsoft.com/en-us/library/435f1dw2.aspx

https://msdn.microsoft.com/en-us/library/aa691135(v=vs.71).aspx

Alan answered 19/5, 2016 at 9:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.