The Action
delegate in C# provides an effective way to encapsulate methods that do not return a value, making it ideal for methods that perform actions, side effects, or procedural logic. This tutorial explains the Action delegate, demonstrates its uses, and explores real-world applications.
The Action
delegate in C# is part of the System namespace and allows you to encapsulate a method that takes from zero to 16 input parameters and does not return any value. It is particularly useful for executing code that performs operations without needing to return a result.
Func
, Action
delegates do not return any value.Action
delegates can handle methods with zero to 16 input parameters, making it flexible for various use cases.The Action
delegate is generic and follows this syntax:
Action<in T1, in T2, ...>
Where, T1
, T2
, ...: Input parameter types.
Action<int, int> displaySum = (x, y) => Console.WriteLine($"Sum: {x + y}");
displaySum(3, 5); // Output: Sum: 8
In this example:
Action<int, int>
defines a delegate with two integer parameters (x
, y
) and no return type.displaySum
lambda expression calculates and displays the sum of two integers.Here, Action
is used to print a simple message, requiring no input parameters.
Action displayMessage = () => Console.WriteLine("Hello, World!");
displayMessage(); // Output: Hello, World!
Action
with no type parameters (Action
) specifies a delegate with no parameters and no return type.() => Console.WriteLine("Hello, World!")
simply prints a message.In this example, Action
is used to display a single number.
Action<int> displayNumber = x => Console.WriteLine($"Number: {x}");
displayNumber(10); // Output: Number: 10
Action<int>
specifies a delegate with one integer parameter.x => Console.WriteLine($"Number: {x}")
prints the provided integer.Action can also be used to perform more complex operations involving multiple parameters.
Action<string, int> greetPerson = (name, age) =>
{
Console.WriteLine($"Hello, {name}! You are {age} years old.");
};
greetPerson("Alice", 30); // Output: Hello, Alice! You are 30 years old.
Action<string, int>
defines a delegate with a string and an integer parameter.(name, age) => Console.WriteLine(...)
outputs a personalized greeting message.A practical use case for Action
is in designing a logging system, where different log levels (info, warning, error) can be handled using Action delegates. This pattern allows for flexible and reusable logging behavior across various parts of an application.
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
// Define logging actions
Action<string> infoLogger = message => Console.WriteLine($"INFO: {message}");
Action<string> warningLogger = message => Console.WriteLine($"WARNING: {message}");
Action<string> errorLogger = message => Console.WriteLine($"ERROR: {message}");
// Sample log messages
infoLogger("Application started.");
warningLogger("Disk space is running low.");
errorLogger("Application encountered a fatal error.");
// Output:
// INFO: Application started.
// WARNING: Disk space is running low.
// ERROR: Application encountered a fatal error.
}
}
infoLogger
: This Action<string>
logs informational messages.warningLogger
: This Action<string>
logs
warning messages.errorLogger
: This Action<string>
logs
error messages.Real-World Use Case: This approach can be used in a modular application to separate different logging behaviors, enabling developers to log different severity levels in various contexts, such as for tracking usage metrics, troubleshooting, or performance monitoring.
Action
delegates are designed for methods that perform actions without returning a result.Action
delegates are perfect for encapsulating reusable procedures, especially those performing side effects or procedural logic.Action
delegates are commonly used in event handlers, logging, and callbacks where no return value is required.The Action
delegate in C# enables developers to encapsulate procedures that require multiple input parameters without returning any result. It is versatile, supporting methods with zero to 16 input parameters, making it suitable for various scenarios, from simple display messages to complex event handling and logging systems. Using Action
delegates not only enhances code readability but also enables a modular approach to method reuse across applications.