Thursday, April 28, 2011

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?

From stackoverflow
  • (x,y) => {} //oops forgot the params
    

    OK? :)

    Or

    delegate {}
    
    Matt Howells : () => {} doesn't work.
  • Try this:

    myClass.Foo += delegate {};
    
  • Attach the event via a lambda like such:

    myClass.Foo += (o, e) => {
        //o is the sender and e is the EventArgs
    };
    
  • myClass.Foo += (s,e) => {};
    

    or

    myClass.Foo += delegate {};
    
  • Try this:

    myClass.Foo += (s,e) => {};
    
  • 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).

    Matt Howells : Yes, but in this case I do not want to assign a default handler.
    Jon Skeet : Fair enough. (Personally I put one in just about every event I declare these days :)
    Matt Howells : 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 :)

0 comments:

Post a Comment