What is Action Delegate in C#: Simple Explanation and Example
Action is a built-in delegate type that represents a method that returns void and can take zero or more input parameters. It allows you to store and pass methods as variables without worrying about return values.How It Works
Think of an Action delegate as a remote control button that can call any method matching its signature, but it doesn't expect any feedback (no return value). You can assign different methods to this button and press it to run those methods whenever you want.
In C#, Action can hold methods that take from zero up to 16 parameters, but always return nothing (void). This makes it useful when you want to run some code later or pass behavior around without caring about results.
Example
This example shows how to use an Action delegate to hold and call a method that prints a message.
using System; class Program { static void Main() { Action greet = () => Console.WriteLine("Hello from Action delegate!"); greet(); Action<string> printMessage = message => Console.WriteLine(message); printMessage("This is a message passed to Action."); } }
When to Use
Use Action when you want to pass a method as a parameter or store it for later execution, especially if you don't need a return value. It's great for callbacks, event handlers, or simple tasks like logging or updating UI.
For example, if you want to run different tasks on a button click or schedule work without caring about results, Action is a clean and easy choice.
Key Points
- Action delegates represent methods that return
void. - They can take zero or more input parameters (up to 16).
- Useful for callbacks, event handling, and passing behavior.
- They simplify code by avoiding explicit delegate declarations.
Key Takeaways
Action delegates hold methods that return no value but can take parameters.Action for callbacks, event handlers, or any void-returning method calls.