What Is the Action Delegate in C# and Its Return Type

This article provides a comprehensive overview of the Action delegate in C#, detailing its fundamental purpose, syntax, and operational mechanics. You will learn what role this built-in delegate plays in the .NET framework, how it simplifies passing methods as arguments, its parameter capabilities, and specifically what type of data it returns.

Understanding the Action Delegate

In C#, a delegate is a type-safe function pointer that references one or more methods with a specific parameter list and return type. Before generic delegates were introduced, developers had to define custom delegates for every unique method signature.

To streamline this, the .NET framework introduced predefined generic delegates in the System namespace. The Action delegate is one of these standard delegates. It is designed to encapsulate a method that takes zero or more input parameters and executes a set of operations without returning a result.

The Return Type of the Action Delegate

The return type of an Action delegate is always void.

Regardless of whether an Action delegate takes no parameters or multiple parameters, it can only point to methods that return nothing. If you need a delegate that returns a value, C# provides the Func delegate family instead.

Syntax and Variations

The Action delegate is overloaded to support anywhere from zero up to 16 input parameters:

  • Action: References a method that takes no parameters and returns void.
  • Action<T>: References a method that takes one parameter of type T and returns void.
  • Action<T1, T2>: References a method that takes two parameters of types T1 and T2 and returns void.
  • This pattern continues up to Action<T1, T2, ..., T16>.

Code Example

using System;

class Program
{
    static void Main()
    {
        // Parameterless Action
        Action greet = () => Console.WriteLine("Hello, World!");
        greet();

        // Action with parameters
        Action<string, int> printPerson = (name, age) => 
        {
            Console.WriteLine($"{name} is {age} years old.");
        };

        printPerson("Alice", 30);
    }
}

When to Use Action

The Action delegate is commonly used in scenarios such as:

  • Callbacks: Passing a notification or follow-up operation to a method that performs work asynchronously or in the background.
  • Event Handling: Executing logic in response to a trigger where no computed value needs to be handed back to the caller.
  • LINQ and Collections: Performing operations on elements in a collection, such as with List<T>.ForEach(Action<T>).