tags:

views:

32

answers:

3

For event handling, I am starting to see many coders doing this:

XButton.Click += OnXButtonClicked()
...
void OnXButtonClicked()
{ ... }

Where did this On_ convention come from? It just doesn't feel right in terms of methods.

I am starting to see this as well and am wondering what others thought:

XButton.Click += HandleXButtonClick()
...
void HandleXButtonClick()
{ ... }

When using intellisense, Visual Studio handles these like so:

XButton.Click += XButton_Click;
...
void XButton_Click(object sender, RoutedEventArgs e)
{ ... }

I am seeking some advice on these naming conventions and would greatly appreciate some advice.

A: 

I recommend using the ObjectName_EventName convention. It is very easy to read and tells you exactly what you need to know, namely which object and which event it is hooked up to

Skywalker
+2  A: 

As these are typically always private methods, the name is really entirely up to you and your team. The event handlers are only used within your private API, and are an implementation detail, which is partly why there isn't any official guidance in terms of naming.

That being said, I would just choose something that makes sense to you and your team, and stick to it for consistency.

Personally, I don't like the "OnXXX" name, as it is somewhat misleading. The suggestion for implementation of events is to use OnXXX as a protected method which raise the event XXX. Using this name as an event handler seems inappropriate.

A HandleXXX name makes sense, given that this is an event subscription, and that method is "handling" the event. The Object_XXX syntax has the advantage of being what the designer in Visual Studio uses by default, so it is also a good choice. That being said, it often conflicts with private variable and method naming schemes (since they're typically lower case) and will make tools like StyleCop complain.

Reed Copsey
Good information! Thanks!
A: 

To have a consistent naming scheme throughout my whole project, I handle it the way Skawalker does as Intellisense does the naming that way.

Marius Schulz