tags:

views:

236

answers:

6
+4  Q: 

No-op lambda

I have an event on one of my classes that I want to attach a handler to. However, I don't need the handler to do anything, as I am just testing the behaviour of the class with handlers attached or not.

The event signature is as follows:

public event EventHandler<EventArgs> Foo;

So I want to do something like:

myClass.Foo += ();

However this isn't a valid lambda expression. What is the most succinct way to express this?

+3  A: 
(x,y) => {} //oops forgot the params

OK? :)

Or

delegate {}
leppie
() => {} doesn't work.
Matt Howells
+3  A: 

Try this:

myClass.Foo += delegate {};
Andrew Hare
+1  A: 

Attach the event via a lambda like such:

myClass.Foo += (o, e) => {
    //o is the sender and e is the EventArgs
};
Andreas Grech
+6  A: 
myClass.Foo += (s,e) => {};

or

myClass.Foo += delegate {};
Matt Howells
+1  A: 

Try this:

myClass.Foo += (s,e) => {};
Arjan Einbu
+1  A: 

Rather than attach a delegate afterwards, the more common way is to do assign it immediately:

public event EventHandler<EventArgs> Foo = delegate {};

I prefer using the anonymous method syntax over a lambda expression here as it will work with various different signatures (admittedly not those with out parameters or return values).

Jon Skeet
Yes, but in this case I do not want to assign a default handler.
Matt Howells
Fair enough. (Personally I put one in just about every event I declare these days :)
Jon Skeet
In this case the class needs to have a different behaviour if it has no handlers attached to the event. If nobody is listening to it it mumbles quietly to itself :)
Matt Howells