The Action delegate lets you store and use methods that do not return a value. It helps you run code later or pass methods as data.
0
0
Action delegate type in C Sharp (C#)
Introduction
When you want to run a method after some event happens, like a button click.
When you want to pass a method to another method to be called inside it.
When you want to store a list of methods to run one by one.
When you want to write cleaner code by avoiding writing separate method calls.
When you want to run code without needing a return value.
Syntax
C Sharp (C#)
Action
Action<T>
Action<T1, T2>
// and so on, up to 16 parametersAction is a delegate type that points to methods with no return value (void).
You can use Action with zero or more input parameters (up to 16).
Examples
A simple Action with no parameters that prints a message.
C Sharp (C#)
Action greet = () => Console.WriteLine("Hello!");
greet();An Action with one string parameter that prints the name.
C Sharp (C#)
Action<string> printName = name => Console.WriteLine($"Name: {name}"); printName("Alice");
An Action with two integer parameters that adds and prints the result.
C Sharp (C#)
Action<int, int> addAndPrint = (a, b) => Console.WriteLine(a + b); addAndPrint(3, 4);
Sample Program
This program shows three Action delegates: one with no parameters, one with one parameter, and one with two parameters. Each prints a message when called.
C Sharp (C#)
using System; class Program { static void Main() { Action sayHello = () => Console.WriteLine("Hello, world!"); Action<string> greet = name => Console.WriteLine($"Hi, {name}!"); Action<int, int> multiplyAndPrint = (x, y) => Console.WriteLine($"{x} * {y} = {x * y}"); sayHello(); greet("Bob"); multiplyAndPrint(5, 6); } }
OutputSuccess
Important Notes
Action delegates always return void, so they cannot return values.
You can use lambda expressions or method groups to assign methods to Action.
Action is useful for callbacks, events, and passing behavior around.
Summary
Action is a delegate type for methods that return nothing (void).
It can take zero or more input parameters (up to 16).
Use Action to store or pass methods that perform actions without returning data.