views:

499

answers:

2

How do you name delegates, events and instance of events?

I use this:

delegate void OnSomethingHandler();
event OnSomethingHandler onSomething;

Is this an accepted way? Notice lower and upper cases


Where do you place delegates and events?

I usually put delegates in an a namespace best reflecting them:

mynamespace.Def.SomethingLike
{

}
mynamespace.Def.SomethingElseLike
{

}


Where do you define events?

I usually place them into the class that uses them.

I notice that a lot of people define delegates and events in the same class. How common is that?

+4  A: 

MSDN on naming events:

Do name events with a verb or a verb phrase.

Do give event names a concept of before and after, using the present and past tense. For example, a close event that is raised before a window is closed would be called Closing and one that is raised after the window is closed would be called Closed.

Do not use Before or After prefixes or suffixes to indicate pre and post events.

Do name event handlers (delegates used as types of events) with the EventHandler suffix.

Do use two parameters named sender and e in event handler signatures.

The sender parameter should be of type Object, and the e parameter should be an instance of or inherit from EventArgs.

Do name event argument classes with the EventArgs suffix.

So, events should be named with a verb or verb phrase. Instead of OnSomething, use Something, assuming that Something is actually a verb, like Close, Click, or ManagedPiplelineAbandoning and ManagedPiplelineAbandoned.

The delegate for an event should be named with the EventHandler suffix, giving CloseEventHandler, ClickEventHandler, ManagedPiplelineAbandoningHandler, etc.

For delegates that aren't related to an event, use a noun, like EventProcessor or ItemRetriever, while an instance of that delegate is a verb, like processEvent or retrieveItem.

The casing of your delegate reference should be camel, unless the reference is not private. I can't think of a case where you'd have a non-private delegate field, though.

bdukes
+1  A: 

Everything you have looks pretty standard - the only thing I would change is that the event name would be Something rather than onSomething. Following Microsofts convention you would end up with something more like this:

delegate void SomethingHandler();
event SomethingHandler Something;

protected void OnSomething()
{
    if (this.Something != null)
        this.Something();
}

And as a cool trick you can add an empty delegate to your Something event so that you don't have to check the event for null before you raise it:

delegate void SomethingHandler();
event SomethingHandler Something = delegate {};

protected void OnSomething()
{
    this.Something();
}
Andrew Hare
I'd consider including the SomethingEventArgs to your sample as that is part of the convention. Also, EventHandler<SomethingEventArgs> is more common post 2.0
Richard Szalay