Search code examples
c#genericsactionfunctorfunc

How to simplify the code with two overloads of the function that get Func and Action as a parameter?


  1. Is it a way to make such code simpler? Yes, I know that the code in the comment can be extracted as a method, but it is a bit confusing to write such two overloads every time. Note that there can be other parameters than functor in a function like DoSomething.

    Result DoSomething<Result>(Func<Parameter, Result> functor)
    {
        // do something to construct argument
        return functor(argument);
    }
    
    void DoSomething(Action<Parameter> functor)
    {
        // do something to construct argument
        functor(argument);
    }
    
  2. More complex variant. How to achieve the same result without code duplication if a functor call is inside a using block?

In fact I want to find a C# alternative to the C++14 code like

template <class Functor>
auto DoSomething(Functor functor)
{
    // do something...
    return functor(argument);
}

Solution

  • Well, you could create a FuncWrapper<Parameter, Result> generic class with implicit conversions from Func<Parameter, Result> and Action<Parameter> and a Call(Parameter) function that performs the actual call.

    The FuncWrapper can have two members (a Func<...> and Action<...>) and call through the one that isn't null, or you can wrap the Action<...> with a lambda expression that essentially turns it into a Func<...> (call the action, return default(Result))

    Then you define just one function in your class:

    Result DoSomething(FuncWrapper<Parameter, Result> wrapper)
    {
        // Find argument
        return wrapper.Call(argument);
    }
    

    Your FuncWrapper class should return default(Result) value in case the Action<Parameter>.