When should anonymous methods be used when defining a delegate and when should formally defined methods be used when defining a delegate ?
When should anonymous methods be used when defining a delegate and when should formally
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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
InternalsVisibleToor a public method, where often you’d normally want it to be private, but such is life.)