c# – Higher-order function returning function returning nothing – Education Career Blog

In C# how do I define function which return function which returns nothing? Something like this:

class X
{
    public Func<void> GetFuncReturningVoid() { ... }
}

,

A function returning nothing is an Action. Using a lambda expression, you could write this:

Action GetFuncReturningVoid() {
    return () => Console.Writeline("my action");
}

And if you need to accept arguments…

Action<int, int> GetActionWithArguments() {
    return (int x, int y) => Console.Writeline(x * y);
}

Or you can let the compiler infer the types:

Action<int, int> GetActionWithArguments() {
    return (x, y) => Console.Writeline(x * y);
}

,

In general, Actions are “actions”: they do something, but return nothing. Funcs are “functions,” in the mathematical sense: they transform one value into another.

So you want something like Action, or Action<T> (for one argument of type T), or Action<T, U>, etc.

Leave a Comment