Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Action as Func in C#

I have a parametric method that takes a Func as an argument

SomeType SomeMethod<T>( Func<T, T> f ) {...}

I would like to pass an Action without having to overload the method. But this takes to the problem, how do you represent and Action as a Func? I tried

Func<void, void>

but its not valid.

like image 446
Cristian Garcia Avatar asked May 30 '14 17:05

Cristian Garcia


1 Answers

You can create an extension method to wrap an action and return a dummy value:

public static class ActionExtensions
{
    public static Func<T, T> ToFunc<T>(this Action<T> act)
    {
        return a => { act(a); return default(T) /*or a*/; };
    }
}

Action<?> act = ...;
SomeMethod(act.ToFunc());

It might be clearer if you create your own Unit type instead of using object and returning null.

like image 54
Lee Avatar answered Nov 03 '22 10:11

Lee