Action<T> Delegate
System.Action<T>
Summary
Represents a delegate that encapsulates a method that takes one parameter and does not return a value.
Remarks
The Action<T> delegate is a generic delegate that is equivalent to the System.Action<T> generic delegate. It's commonly used for passing callbacks or event handlers that require a single input parameter and have no return value.
You can use the Action<T> delegate to pass a method as a parameter without having to declare a custom delegate. For example, the following code defines a lambda expression that accepts an integer and writes it to the console, and then passes this lambda expression to a method that takes an Action<int> delegate.
Syntax
public delegate void Action<in T>(T obj);
Type Parameters
| Name | Description |
|---|---|
T |
The type of the parameter of the method that this delegate encapsulates. |
Methods
The Action<T> delegate inherits from the System.Delegate class, which provides the following methods:
public static Delegate Combine(Delegate a, Delegate b): Combines two delegates.public static Delegate Combine(params Delegate[] value): Combines an array of delegates.public static Delegate Remove(Delegate source, Delegate value): Removes a delegate from another delegate.public static Delegate RemoveAll(Delegate source, Delegate value): Removes all occurrences of a delegate from another delegate.public object DynamicInvoke(params object[] args): Dynamically invokes the delegate with the specified arguments.public MethodInfo Method { get; }: Gets the method represented by the delegate.public object Target { get; }: Gets the object on which the delegate instance is invoked.
Examples
Using Action<T> with a Lambda Expression
using System;
public class Example
{
public static void Main(string[] args)
{
Action<string> greet = (name) => Console.WriteLine($"Hello, {name}!");
greet("World"); // Output: Hello, World!
Action<int> printSquare = (number) => Console.WriteLine($"The square of {number} is {number * number}");
printSquare(5); // Output: The square of 5 is 25
}
}
Using Action<T> with a Method
using System;
public class Example
{
public static void PrintMessage(string message)
{
Console.WriteLine($"Message: {message}");
}
public static void Main(string[] args)
{
Action<string> messageHandler = PrintMessage;
messageHandler("This is a test."); // Output: Message: This is a test.
}
}