I'm trying to pass parameter, which is anonymous delegate (no input parameters, no return value), to function.
Something like this:
private function DoSomething(delegate cmd)
{
cmd();
}
Then, I'm want to use this function to call function in this way:
DoSomething(delegate
{
Console.WriteLine("Hooah!");
});
I'm want this specific way, because it's easy to use writing style.
Possible?
Exactly for such purposes Microsoft has created the Action and Func wrapper classes in the .NET framework. Both classes are relying on anonymous functions. Use Action if you don't need to return any result, just to execute the anonymous function:
It can be used like this:
The
() =>
term is a lambda expression and means something likeinput with no parameters is calling ...
. See the documentation for a thorough explanation.If you want to return a result, then use the Func delegate:
Usage:
Both wrappers have overrides that accept up to 8 parameters.
When using Func, the last parameter is always the return type:
The Func wrapper can be used directly with a typed parameter:
I often use Func's in order to create a generic executor that is wrapped in a try/catch block and logging if something happens. This way i reduce the repetative code:
Usage:
You could still use the original delegate concept. The Action and the Func classes are just wrappers around predefined generic delegate methods.