Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the prefix "On" in the name of the C# methods imply anything?

Can anyone help me with this confusion? Is there a special meaning associated with the methods that I see in C# examples, 3rd party software, specially the methods handling events, that start with the Prefix "On"?

In other words is this a Language convention? Recommendation ? or KeyWord?

Thanks for your help.

like image 714
user1298925 Avatar asked Sep 09 '13 17:09

user1298925


2 Answers

It is convention that a method that exists to fire an event would be prefixed with "On", i.e. OnSomeEvent, when called, would fire the SomeEvent event. There is no keyword or other language construct that would force the use of the "On" prefix; it's merely a convention.

Creating such a method is also usually used when you need to allow the event to be fired explicitly from outside the class definition (usually from inheriting classes, hence why these methods are usually protected). If the class is designed such that the event is only ever fired from within the class that defines it, there usually won't be any "On" method, which is why you don't see one in many cases.

like image 66
Servy Avatar answered Oct 17 '22 23:10

Servy


As per comments:

Thank you . Do u happen to know about any URL on what you added. I wold need more clarifications to understnad it.

This is just to explain that; as a full example of the general case, this is the established convention - not a rule - there is noting to enforce this - it is just a common pattern that a lot of code uses:

public class SomeBaseClassWithAnEvent
{
    public event EventHandler SomeEvent;

    protected virtual void OnSomeEvent()
    {
        var handler = SomeEvent;
        if (handler != null) handler(this, EventArgs.Empty);
    }

    public void SomeOtherMethodThatHasSideEvents()
    {
        //...do stuff...
        OnSomeEvent();
        //...do more stuff...
    }
}

public class SomeSubclass : SomeBaseClassWithAnEvent
{
    protected override void OnSomeEvent()
    {
        // custom stuff here to do it before the event
        base.OnSomeEvent();
        // or here to do it after the event
    }
}

This pattern allows two things:

  • the subclass can invoke the event by calling the On... method
  • the subclass can intercept the event to add functionality by overriding the On... method

And if you want to see how ingrained this pattern is - just go into whatever framework you are using (winforms, wpf, asp.net, asp.net mvc, whatever else you can think of) and just type override, then scroll down to On:

enter image description here

(hint... that scroll bar goes for quite a while in the On... range)

like image 10
Marc Gravell Avatar answered Oct 17 '22 23:10

Marc Gravell