.NET API Reference

Func<T, TResult> Delegate

public delegate TResult Func<in T, out TResult>(T arg);

Summary

Represents a function that accepts one argument and produces a result.

Parameters

  • T arg
    The argument of the function.

Returns

  • TResult
    The result of the function.

Remarks

The Func<T, TResult> delegate is a generic delegate that defines the signature of a method that takes one parameter of type T and returns a result of type TResult.

This delegate is commonly used with lambda expressions and anonymous methods to represent operations that transform an input value into an output value.

Example

using System;

public class Example
{
    public static void Main(string[] args)
    {
        // Define a Func delegate that takes an integer and returns its square
        Func<int, int> square = x => x * x;

        int number = 5;
        int result = square(number); // result will be 25

        Console.WriteLine($"The square of {number} is {result}");

        // Define a Func delegate that takes a string and returns its length
        Func<string, int> getStringLength = s => s.Length;

        string text = "Hello, World!";
        int length = getStringLength(text); // length will be 13

        Console.WriteLine($"The length of \"{text}\" is {length}");
    }
}