Monday 15 March 2010

c# - When is it better practice to explicitly use the delegate keyword instead of a lambda? -


Representative In relation to the explicit use of the keyword, there is no best practice regarding coding style: a lambda Instead of using

example

  new thread ((=) = {// work item 1 / work item 2}). New thread (rep () {// work item 1 / work item 2}). Start ();  

I think lambda looks better if lambda is better style, compared to the fact that lambda is in existence before it is applied, besides a representative keyword?

The lambda syntax is more generalized, and designers have said that they want to remove the old overlapping syntax (no quote, but maybe it is Eric Lipton or John) < / P>

};

Versus Speaking:

  object.Event + = (Sender, Args) => {};  

That can be very useful in large logic lists and / or to make the code more flexible for refactoring.

Edit: As mentioned in another answer (now unfortunately deleted), a very streamlined use of this trick is to provide a default hander for an event using the Null Object pattern. For: -

  class MyClassThatFiresWithoutTheTrick {Public Event EventHandler MyEvent; // implicit = null // One method is required to keep this dry because each fire requires a redundant check - see the Abrams and framework design guidelines. Virtual zero overview () {// is required to be protected. // See C # 3 version P664-5 through CRL Reason Why this work is / var handler = MyEvent; // But this preferred version is Var Handler = Interlock Compressed Exchange (Ref: MyAvent, blank, blank); // This check is required because it can not be override if (handler == blank) return; Handler (this, EventArgs.Empty); }} Category MyClassThatFiresWithTheTrick {Public Event EventHandler MyEvent = delegate {}; Protected Virtual Zones OnMyEvent () {MyEvent (This, EventArgs.Empty); }}  

(Although you can often do that which is an inline method of OnMyEvent , the code is even smaller again.)


No comments:

Post a Comment