Search code examples
c#delegatesparameter-passingfunc

In C#, how do I replace a Func with a delegate in a function parameter?


Looking at the following function that expects another Function with an output type T and simply calls it at returns the result:

T CallFunction<T>(Func<T> lambda)
{
  return lambda();
}

I would expect that I could replace Func<T> lambda with delegate T lambda<T>(). However that seems not possible, I cannot do something like:

T CallFunction<T>(delegate T lambda<T>())
{
  return lambda();
}

or:

delegate T MyLambda<T>();

T CallFunction<T>(MyLambda lambda)
{
  return lambda();
}

Is just my syntax wrong or do I not fully understand yet what Delegate and Func is? Isn't Func<T> lambda just a delegate that returns type T in this case?


Solution

  • You're almost there, the lambda is a generic delegate and you have to provide the generic argument

    delegate T MyLambda<T>();
    
    T CallFunction<T>(MyLambda<T> lambda)
    {
      return lambda();
    }
    

    Note

    T CallFunction<T>(MyLambda<T> lambda)
    

    instead of yours

    T CallFunction<T>(MyLambda lambda)
    

    The the first attempt

    T CallFunction<T>(delegate T lambda<T>())
    

    is illegal as it would introduce a new type in a function parameter declaration. The delegate keyword can be used when defining an anonymous function (to be passed as an argument) but it cannot be used to declare a parameter type. In other words, you could call the CallFunction passing an anonymous delegate

    CallFunction<int>( delegate { return 1; } );