Friday, October 25, 2024

Action Delegate Explanation in C#

In C#, an Action delegate is a predefined delegate type provided by the .NET Framework that represents a method that does not return a value (void) and can optionally take parameters. It is defined in the System namespace.

The Action delegate can be used to encapsulate a method that takes zero to sixteen input parameters and does not return a value. It is typically used for scenarios where you want to execute a piece of code without expecting any result.

Here's the general syntax for using the Action delegate:
Action parameters = (parameter1, parameter2, ...) => {
    // Code to be executed
};
You can use the Action delegate to create a method reference and execute it later. Here's an example of how you can use the Action delegate to encapsulate a method and invoke it:
using System;

class Program
{
    static void Main(string[] args)
    {
        // Example: Using Action delegate with no parameters
        Action myAction = () => {
            Console.WriteLine("Action executed.");
        };

        // Invoke the action
        myAction();

        // Example: Using Action delegate with parameters
        Action<string> greetAction = (name) => {
            Console.WriteLine("Hello, " + name);
        };

        // Invoke the action with a parameter
        greetAction("John");

        // Example: Using Action delegate with multiple parameters
        Action<string, int> displayInfoAction = (name, age) => {
            Console.WriteLine("Name: " + name + ", Age: " + age);
        };

        // Invoke the action with multiple parameters
        displayInfoAction("Alice", 30);
    }
}

In this example:
  • We define an Action delegate without any parameters and assign a lambda expression to it.
  • We define an Action delegate with a single parameter (a string) and assign a lambda expression to it.
  • We define an Action delegate with two parameters (a string and an int) and assign a lambda expression to it.

You can invoke the Action delegate by simply calling it like a method, passing any required parameters.

Note: Action is a delegate type defined by the .NET Framework and is available in the System namespace.

No comments:

Post a Comment

Hot Topics