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.
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.
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:
On...
methodOn...
methodAnd 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
:
(hint... that scroll bar goes for quite a while in the On...
range)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With