0

Hi, all

I have some code as shown below:

public class Child : Parent
{
    public event Action<string> OnEventTriggered;
}

public class Parent
{
    protected virtual void OnEventTriggered( double x ) { }
}

The compiler shows warning message:

'Child.OnEventTriggered' hides inherited member 'Parent.OnEventTriggered(double)'. Use the new keyword if hiding was intended.

Virtual method shares the same name with that of event.

Param type of the virtual method is double, and Action is string type.

Why does it violate the checking rule?

Thanks for answering in advance.


Additional scenario:

If I change the code to this, it doesn't show any warning.

What's the difference between these code?

public class Child : Parent
{
    public void OnEventTriggered( string x ) { }
}

public class Parent
{
    protected virtual void OnEventTriggered( double x ) { }
}
Sean
  • 29
  • 3
  • Possible duplicate of [Use new keyword if hiding was intended](http://stackoverflow.com/questions/451035/use-new-keyword-if-hiding-was-intended) – Win Oct 04 '16 at 14:44

1 Answers1

2

Because the name is identical. Since you do not add any override or new keywords, the compiler assumes you were not aware of the base class property/method, and gives you a warning.

  • Use override if you want to override the base class property/method. For this the types and name must match. This property/method can be called from the base class.
  • Use new if you want to create a completely new property/method. This new property/method cannot be called from the base class.

Change the name of the event in the derived class, and the rule won't be violated.

Normally an event is implemented in the following way, all in the same class:

public class EventDemo {
    public event EventHandler SomeEvent;

    protected virtual void OnSomeEvent() {
        var someEvent = SomeEvent;
        if (someEvent != null) {
            someEvent(this, EventArgs.Empty);
        }
    }
}
Maarten
  • 22,527
  • 3
  • 47
  • 68
  • Thanks for answering. In my question, The type of Action is string, and the virtual method has double input. These types are not match. Will compiler still take them as the same? – Sean Oct 04 '16 at 14:57
  • Although using the same name for different things is a real bad practice, technically seems unjustified forbidding it. That is, in the same class, you can't have a property an a method with the same name. My only guess is about the portability of the assembly throughout other languages, such as VB, where the syntax would break. – Mario Vernari Oct 04 '16 at 15:29
  • @MarioVernari Who says it is, or where is it stated to be, forbidden? – Maarten Oct 04 '16 at 17:47
  • @Maarten try yourself: won't compile! that's because I wonder why a similar constraint. A warning for a naming match is a very good thing, though. – Mario Vernari Oct 05 '16 at 03:47