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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With