Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C#

System.Func — delegates that return a value

System.Func is a family of generic delegates representing operations that return a value. It lets you store and pass methods or lambdas without defining a custom delegate type.

Version: .NET 10; repository net10.0 and LangVersion=preview; feature versions require per-entry verification

Syntax

Func<TResult> name = () => result;
Func<T, TResult> name = argument => result;

System.Func denotes a family of generic delegate types, not a single nongeneric type. In Func<T, TResult>, type parameter T specifies the argument type, and the final type parameter, TResult, specifies the result type.

You can assign a compatible method or lambda to a variable. square(5) invokes the stored delegate; assigning the lambda alone does not execute its body.

Func<TResult> takes no arguments but still returns a value. For an operation with one argument and a void return, use Action<T>, not Func<T, void>.

In the example, square accepts an int and returns an int, while answer only returns an int. The expected output is 25 and 42 on separate lines.

Examples

using System;

internal static class Program
{
    private static void Main()
    {
        Func<int, int> square = x => x * x;
        Func<int> answer = () => 42;

        Console.WriteLine(square(5));
        Console.WriteLine(answer());
    }
}

Result

25
42

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources