This tutorial aims to provide a comprehensive guide on using Action, Func, and Predicate Delegates in C#. These delegates represent methods with different signatures and usage that can make your code more flexible and generic.
By the end of this tutorial, you will understand the following concepts:
- What are Action, Func, and Predicate delegates
- How to use these delegates in your C# programs
Before getting started, you should have a basic understanding of C# programming and its syntax.
The Action delegate in C# represents a method that contains a void return type and optionally has parameters.
Example:
// Define an Action delegate
Action<string> display = delegate(string message)
{
Console.WriteLine(message);
};
// Use the delegate
display("Hello, World!");
Func delegate represents a function that can take up to 16 input parameters and returns a value. The last type parameter is always the result.
Example:
// Define a Func delegate
Func<int, int, int> add = delegate(int a, int b)
{
return a + b;
};
// Use the delegate
int result = add(10, 20);
Console.WriteLine(result); // Outputs 30
Predicate delegate represents a method that takes one input parameter and returns a boolean value.
Example:
// Define a Predicate delegate
Predicate<string> isUpper = IsUpperCase;
bool result = isUpper("hello");
Console.WriteLine(result); // Outputs False
public static bool IsUpperCase(string str)
{
return str.Equals(str.ToUpper());
}
Let's take a look at some more detailed examples:
Action<int, int> calculate = (a, b) =>
{
Console.WriteLine($"Sum: {a + b}");
Console.WriteLine($"Difference: {a - b}");
};
calculate(10, 5);
// Outputs:
// Sum: 15
// Difference: 5
Func<int, int, int> multiply = (a, b) => a * b;
int product = multiply(10, 2);
Console.WriteLine($"Product: {product}"); // Outputs: Product: 20
Predicate<int> isEven = n => n % 2 == 0;
bool result = isEven(4);
Console.WriteLine($"Is Even: {result}"); // Outputs: Is Even: True
In this tutorial, we covered:
Next, you can explore more about delegates and their use cases in C#. For more information, refer to the Microsoft C# Delegates Documentation.
Func
delegate that takes two strings and returns their concatenation.Predicate
delegate that checks if a number is a prime number.Action
delegate that prints square of a number.Func<string, string, string> concatenate = (a, b) => a + b;
string result = concatenate("Hello, ", "World!");
Console.WriteLine(result); // Outputs: Hello, World!
Predicate<int> isPrime = n =>
{
if (n <= 1) return false;
for (int i = 2; i * i <= n; i++)
{
if (n % i == 0) return false;
}
return true;
};
bool result = isPrime(7);
Console.WriteLine(result); // Outputs: True
Action<int> printSquare = n => Console.WriteLine(n * n);
printSquare(5); // Outputs: 25