What is Func Delegate in C#: Simple Explanation and Example
Func is a built-in delegate type that represents a method returning a value and optionally taking parameters. It allows you to store or pass methods as variables, making your code more flexible and reusable.How It Works
Think of Func as a container that can hold a recipe (a method) which takes some ingredients (input parameters) and gives you a finished dish (a return value). Instead of calling the recipe directly, you keep it in this container and decide when to use it.
This means you can pass around methods as if they were data. For example, you can give a method to another method to use later, or store it in a list to call multiple times. Func delegates always return a value, and you can specify how many inputs they take (from zero up to sixteen).
It’s like having a remote control for a machine: you don’t need to know how the machine works inside, just press the button (call the delegate) and get the result.
Example
This example shows how to use a Func delegate to hold a method that adds two numbers and returns the sum.
using System; class Program { static void Main() { // Func delegate that takes two ints and returns an int Func<int, int, int> add = (x, y) => x + y; int result = add(5, 3); Console.WriteLine($"Sum: {result}"); } }
When to Use
Use Func when you want to pass methods as arguments, store them in variables, or return them from other methods. This is helpful for creating flexible and reusable code, such as in sorting, filtering, or processing collections.
For example, you might use Func to define a custom rule for filtering a list of items without writing a new method each time. It’s also common in LINQ queries and asynchronous programming where you want to specify what to do with data dynamically.
Key Points
- Func is a delegate that always returns a value.
- It can take zero or more input parameters (up to 16).
- It is useful for passing methods as variables.
- Commonly used in LINQ and functional programming styles.
- Helps make code more flexible and reusable.