Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# delegate definition - anonymous methods vs. formally defined methods

When should anonymous methods be used when defining a delegate and when should formally defined methods be used when defining a delegate ?

like image 495
Scott Davies Avatar asked Dec 05 '22 05:12

Scott Davies


2 Answers

If you need to use the same logic in more than one place, it makes sense to use a separate method.

If you only need to use the logic once and it's fairly short, it makes sense to use an anonymous function. If the delegate needs access to local variables in the method which is creating it, anonymous functions act as closures which can also be very handy.

Additionally, an anonymous function can be useful even if it's reasonably long if it's used for something like parallelization with Parallel Extensions - part of the point of that is that you can take existing serial code and parallelise it "in place" to a large extent.

You might also want to consider testability - if your delegate's code is sufficiently complicated that it warrants its own unit tests, exposing it as a method makes a lot of sense. (Unfortunately it would have to be either an internal method using InternalsVisibleTo or a public method, where often you'd normally want it to be private, but such is life.)

like image 187
Jon Skeet Avatar answered Dec 09 '22 14:12

Jon Skeet


I use anonymous methods when the function that should be executed, should only be executed by that delegate (in other words: when I do not need that function in any other place), and, when the function/method that has to be executed is relatively short (5 lines max.).

But, there are no strict rules defined when to use what.
IMHO, I find that anonymous methods do not contribute to readability in most of the situations, so I mostly do not use them.

like image 39
Frederik Gheysels Avatar answered Dec 09 '22 15:12

Frederik Gheysels