odiseh
odiseh

Reputation: 26537

C#: How the Event handler is bound to a method named "On....."?

hi all My friend says "in c#, every event handler is bound to a method which its name is On...." I mean, for example, SelectedIndexChanged of a combobox is bound to a method named OnSelectedIndexChanged.

My question is: How can I see it?

Please tell me more about that if its possible.

Thank you

Upvotes: 1

Views: 392

Answers (3)

Liviu Mandras
Liviu Mandras

Reputation: 6627

The methods that start with "On...." are used as a convention. These methods are not "bound" in any way with an event nor an event is "bound" to them (taking into consideration the generally accepted definition/procedure of registering for an event).

What they actually do is raise the event suggested by the words following the "On" prefix.

For instance:

protected void OnSelectedIndexChanged(EventArgs e)
{
   if(SelectedIndexChanged!= null)
      SelectedIndexChanged(this, e);
}

where SelectedIndexChanged event is defined somewhere like this:

public event EventHandler SelectedIndexChanged;

The convention and .net practices state that for each event you should have a overridable protected method that raises the event.

In a derived class you could do something like that:

protected override void OnSelectedIndexChanged(EventArgs e)
{
   base.OnSelectedIndexChanged(e);

   // your custom code here
}

NOTE: To be absolutely correct, this event and others may use different derived types from the EventArgs class but the concept is the same.

Upvotes: 1

Euphoric
Euphoric

Reputation: 12849

This is class design convention, not something .NET enforces. Most of .NET and 3rd party libraries use this convention. Its simply code, that needs to be coded to meet this convention. Its not automatic, if you wanted to ask that.

Upvotes: 2

anon
anon

Reputation:

Your statement is not entirely true.

You can bound any method to the event as long as that method has the required signature. Not every event is bounded to a method, and not every method bounded to an event starts with "Onxxx". The naming convention is quite popular among developers though. (by default Visual Studio naming convention is [Name of the component]_[Name of the event].

You can see which methods are bounded to which events from the design view, Properties subpanel, select the event tab (icon similar to a storm light). You will have the list of events and the method bounded to it (if there is one)

Upvotes: 2

Related Questions