In C#, Action is a built-in generic delegate type that represents a method that does not return a value. It is used when you only need to perform an action but don’t need a result back.
- Defined in the System namespace.
- Can take zero to sixteen input parameters.
- Always returns void.
- If a delegate should return a value, use Func instead.
Syntax:
Action<T1, T2, ...> variableName = method_or_lambda;
- T1, T2, ... : Input parameter types.
- No return type parameter because Action always returns
void.
Example 1: Action with No Parameters
An Action delegate can represent a method that takes no parameters and returns nothing.
Action greet = () => Console.WriteLine("Hello from Action!");
greet();
Output:
Hello from Action!
Here greet is an Action delegate with no parameters. When invoked, it simply executes the lambda expression and prints a message.
Example 2: Action with One Parameter
You can define Action delegates that accept input parameters.
Action<string> printMessage = msg => Console.WriteLine(msg);
printMessage("Welcome to C# Action delegates");
Output:
Welcome to C# Action delegates
This Action takes a single string parameter and prints it. The delegate type is Action<string> because it accepts one string input.
Example 3: Action with Two Parameters
Action delegates can handle multiple input parameters (up to 16).
Action<int, int> displaySum = (a, b) => Console.WriteLine($"Sum: {a + b}");
displaySum(5, 8);
Output:
Sum : 13
The delegate accepts two integers and prints their sum. No return value is expected because Action always returns void.
Example 4: Action with Multiple Statements
You can use braces {} if more logic is needed.
Action<string> processName = name => {
string upper = name.ToUpper();
Console.WriteLine($"Processed Name: {upper}");
};
processName("john");
Output:
Processed Name: JOHN
This Action takes a string input, converts it to uppercase and then prints it. The block body allows adding extra steps inside the delegate.
Example 5: Action with Named Method
You can assign an Action delegate to a method.
class Program {
static void ShowMessage(string msg) {
Console.WriteLine(msg);
}
static void Main() {
Action<string> action = ShowMessage;
action("Hello using named method");
}
}
Output:
Hello using named method
Here the ShowMessage method matches the Action<string> delegate signature, so it can be assigned directly and invoked using the delegate.
Example 6: Action with Collections (LINQ)
Action is often used in ForEach loops with collections.
List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
numbers.ForEach(n => Console.WriteLine($"Number: {n}"));
Output:
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
The ForEach method expects an Action delegate. Here, each element of the list is passed to the Action, which prints the number to the console.