Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it a good practice to define an empty delegate body for a event? [duplicate]

Tags:

Possible Duplicate:
Is there a downside to adding an anonymous empty delegate on event declaration?

Is it a good practice to define an empty delegate body for a event so that you do not need to worry raise a event which have no event handler? ( no need to check whether event is null).

Like code below:

public event EventHandler<LoadEventArgs> LoadedData = delegate { }; 
like image 959
Kurt Liu Avatar asked Nov 29 '10 11:11

Kurt Liu


People also ask

Can we use events without delegates?

Yes, you can declare an event without declaring a delegate by using Action. Action is in the System namespace.

What is the difference between delegate and event?

A delegate specifies a TYPE (such as a class , or an interface does), whereas an event is just a kind of MEMBER (such as fields, properties, etc). And, just like any other kind of member an event also has a type. Yet, in the case of an event, the type of the event must be specified by a delegate.

What is an event and a delegate ?- How are they related?

Delegate is a type that defines a signature and holds a reference of method whose signature matches with the delegate. Event is a notification raised by an object to signal the occurrence of an action. Delegate is associated with the event to hold a reference of a method to be called when the event is raised.


1 Answers

I've certainly found it useful, yes. There will be a tiny, tiny performance cost - but the benefit in readability for not having to perform the nullity test makes it worth it IMO.

It's worth pointing out that this is one of the few times when it's good to use an anonymous method rather than a lambda expression - otherwise you have to name the parameters that you're going to ignore, like this:

public event EventHandler<LoadEventArgs> LoadedData = (sender, args) => {}; 

I don't like having to name things I'm not intending to use :)

like image 116
Jon Skeet Avatar answered Sep 18 '22 13:09

Jon Skeet