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

88 Views Asked by At

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?

2

There are 2 best solutions below

6
Wiktor Zychla On BEST ANSWER

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; } );
3
Guru Stron On

Func<T> itself is a delegate:

public delegate TResult Func<out TResult>();

And the second substitute attempt is missing generic parameter for the MyLambda delegate (the same as you do with Func<T> in T CallFunction<T>(Func<T> lambda)):

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