![]() |
VOOZH | about |
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.
Syntax:
Action<T1, T2, ...> variableName = method_or_lambda;
void.An Action delegate can represent a method that takes no parameters and returns nothing.
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.
You can define Action delegates that accept input parameters.
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.
Action delegates can handle multiple input parameters (up to 16).
Output:
Sum : 13
The delegate accepts two integers and prints their sum. No return value is expected because Action always returns void.
You can use braces {} if more logic is needed.
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.
You can assign an Action delegate to a 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.
Action is often used in ForEach loops with collections.
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.