I’ve been writing a lot of C# middleware lately and it’s not uncommon to have a need for throwaway delegates.
For example:
While this works fine, it leaves one with the “You’re doing it wrong” feeling. After working on a project where it became obvious I was going to require hundreds of these throwaway delegates I started to do some digging. In .Net 3.5, Microsoft introduced the Action and Func delegates. These utilize generics to generate these throwaway delegates in a clear manner.
The example above becomes:
This in itself isn’t too drastic of a change since it is such a trivial example. When you add in multiple developers, each with their own shorthand for creating throwaway delegates is where you’ll be happy you used them.
One thing to keep in mind is that in .Net 3.5, the Action and Func delegates were limited to 4 parameters. In .Net 4.0 this has been extended to 9. In the case that you are limited to 3.5 or are working against an insane API that requires 12 parameters to do anything, you can easily roll your own variations of these same delegates.
If you want to get tricky and start accepting out or ref parameters, you can as well:
But at this point you need to start coming up with your own name for the generic versions of the delegates which begins to create the multiple developer shorthand issue again. Another thing to keep in mind is that the out parameters will be changed in the array you pass to the Delegate invocation method but not whatever populated the array in the first place.