Func<TResult> Delegate
Represents a function that accepts no arguments and returns the value of the specified type.
public delegate TResult Func<TResult>();
Type Parameters
- TResult: The type of the result of the function.
Remarks
- The
Func<TResult>delegate is a generic delegate type that represents a function with no input parameters and a return value of typeTResult. - It is commonly used in scenarios where you need to pass a method or lambda expression that produces a value without taking any arguments.
- For delegates that accept one or more input arguments, use the
Func<T, TResult>,Func<T1, T2, TResult>, and so on, up toFunc<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, TResult>delegates. - The
Actiondelegates are used for operations that do not return a value.
Example
The following example demonstrates how to use the Func<TResult> delegate to represent a method that returns a random number.
using System;
public class Example
{
public static void Main(string[] args)
{
// Define a Func delegate that returns a double
Func<double> getRandomNumber = () => Math.PI * Math.Sqrt(100);
// Invoke the delegate
double result = getRandomNumber();
Console.WriteLine($"The random number is: {result}");
// Another example with a method
Func<string> sayHello = GetGreeting;
Console.WriteLine(sayHello());
}
public static string GetGreeting()
{
return "Hello from the Func delegate!";
}
}