Example
class Example {
public static int method(int num)
{
return num + num;
}
static public void Main()
{
Func<int, int> myfun = method;
Console.WriteLine(myfun(10));
}
}
Output:
20
Func Delegate With Anonymous Methord
An anonymous method can also be used with a Func delegate. As seen in the case below.
Example:
Func<int, int, int> val = delegate(int x, int y, int z)
{
return x + y + z;
};
Func Delegate With Lambda Expressions
With lambda expressions, you may also utilize a Func delegate. As seen in the case below.
Example:
Func<int, int, int, int> val = (int x, int y, int z) = > x + y + z;
Frequently Asked Questions
The last parameter in Func delegate represents?
The last parameter in the Func delegate represents the return type. You need to specify the return type at the end of the parameters.
In which namespace Func delegate is specified?
Function delegate is specified in the System namespace. System.Runtime.dll. Encapsulates a single-parameter method that returns a result of the type defined by the TResult parameter.
How many parameters can a Func delegate accept?
It can have as less as 0 input parameters and as many as 16 input parameters, but only one output parameter. The Func delegate's final parameter is the out argument, which is a return type and is used for the outcome.
Can Func delegate be used with an anonymous function?
Yes, you can use Fun delegate with an anonymous function. The function delegate does not support ref and out arguments. An anonymous method or lambda expression can be utilized with the Func delegate type.
Can Func delegate be used with lambda expression?
Yes, Func delegate can be used with a lambda expression. An anonymous method or lambda expression can be utilized with the Func delegate type.
Conclusion
In this article, we had a look at Func Delegate in C# and learned its implementation. We hope that this blog has helped you enhance your knowledge regarding Func Delegate and if you would like to learn more, check out Delegates in C# and Methods in C# also other articles on Coding Ninjas Studio.
Recommended Readings:
Do upvote our blog to help other ninjas grow. Happy Coding!