Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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; } );
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading