02 November 2011

C# - Inline event handler

Sometimes an event handler is short enough for it to just put it inline, thus saving yet another method from being created. Let's say I have a custom event called OkEventHandler thats part of an object called RenameWindow. I attach the handler as follows:
renameWnd.Ok += new RenameWindow.OkEventHandler(delegate(object sender, EventArgs e) {
  //Whatever needs to be done
});
Or shorter:
renameWnd.Ok += (object sender, EventArgs e) => {
  //Whatever needs to be done
};
And even shorter:
renameWnd.Ok += delegate {
  //Whatever needs to be done
};
How much shorter can it get?
renameWnd.Ok += (sender, e) => DoOneThing();
Not much to it once you know.

No comments:

Post a Comment