0
0
C Sharp (C#)programming~5 mins

Func delegate type in C Sharp (C#)

Choose your learning style9 modes available
Introduction

The Func delegate lets you store and use methods that return a value. It helps you pass around small pieces of work easily.

When you want to pass a method as a parameter that returns a result.
When you need to store a method in a variable to call it later.
When you want to write cleaner code by using inline functions.
When you want to use methods with different input types but a return value.
When you want to simplify callbacks that return data.
Syntax
C Sharp (C#)
Func<T1, T2, ..., TResult> variableName = methodName;
// or
Func<T1, T2, ..., TResult> variableName = (parameters) => expression;

Func can have 0 to 16 input parameters.

The last type parameter is always the return type.

Examples
This Func takes one int and returns its square.
C Sharp (C#)
Func<int, int> square = x => x * x;
This Func takes two int values and returns their sum.
C Sharp (C#)
Func<int, int, int> add = (a, b) => a + b;
This Func takes no input and returns a greeting string.
C Sharp (C#)
Func<string> greet = () => "Hello!";
Sample Program

This program creates a Func that multiplies two numbers. It then calls it with 4 and 5 and prints the result.

C Sharp (C#)
using System;

class Program
{
    static void Main()
    {
        Func<int, int, int> multiply = (x, y) => x * y;
        int result = multiply(4, 5);
        Console.WriteLine($"4 times 5 is {result}");
    }
}
OutputSuccess
Important Notes

You can use Func to simplify code that needs small reusable methods.

Remember, the last type parameter is always the return type, others are inputs.

Func is built-in and saves you from writing custom delegate types.

Summary

Func stores methods that return a value.

It can have multiple inputs but only one output.

Use it to pass or store small functions easily.