When should anonymous methods be used when defining a delegate and when should formally defined methods be used when defining a delegate ?
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.)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With