I'm learning about Events / Delegates in C#. Could I ask your opinion on the naming/coding style I've chosen (taken from the Head First C# book)?
Am teaching a friend about this tomorrow, and am trying to come up with the most elegant way of explaining the concepts. (thought the best way to understand a subject is to try and teach it!)
class Program
{
static void Main()
{
// setup the metronome and make sure the EventHandler delegate is ready
Metronome metronome = new Metronome();
// wires up the metronome_Tick method to the EventHandler delegate
Listener listener = new Listener(metronome);
metronome.OnTick();
}
}
public class Metronome
{
// a delegate
// so every time Tick is called, the runtime calls another method
// in this case Listener.metronome_Tick
public event EventHandler Tick;
public void OnTick()
{
while (true)
{
Thread.Sleep(2000);
// because using EventHandler delegate, need to include the sending object and eventargs
// although we are not using them
Tick(this, EventArgs.Empty);
}
}
}
public class Listener
{
public Listener(Metronome metronome)
{
metronome.Tick += new EventHandler(metronome_Tick);
}
private void metronome_Tick(object sender, EventArgs e)
{
Console.WriteLine("Heard it");
}
}
n.b. Code is refactored from http://www.codeproject.com/KB/cs/simplesteventexample.aspx
Looks good, aside from the fact that
OnTick
doesn't follow the typical event invocation model. Typically,On[EventName]
raises the event a single time, likeConsider creating this method, and renaming your existing "
OnTick
" method to "StartTick
", and instead of invokingTick
directly fromStartTick
, callOnTick(EventArgs.Empty)
from theStartTick
method.Interesting how Microsoft seems to break its own naming conventions with Visual Studio generated event handler names.
See: Event Naming Guidelines (.NET Framework 1.1)
A point I have found after using events in .Net for many years is the repetitive need to check the event for a null handler on every invocation. I'm yet to see a piece of live code that does anything but not call the event if it is null.
What I have started doing is to put a dummy handler on every event I create to save the need to do the null check.
In your case it could be:
Above sampple use below convention, self-describing ;]
Events source:
BTW. keyword
event
is optional but enables distinguishing 'events' from 'callbacks'Events listener:
And binding [code looks human friendly]
Even manually sending events is "human readable".
Sometimes more expressive can be "verb + ing"
Whichever convention you choose, be consistent with it.
I would say the best guide to events in general, including naming conventions, is here.
It is the convention I have adopted, briefly:
Microsoft has actually written extensive set of naming guidelines and put it in the MSDN library. You can find the articles here: Guidelines for Names
Aside from the general capitalization guidelines, here is what it has for 'Events' on the page Names of Type Members: