What is Action in CSharp?

Read an interesting article today from debugmode.net.  The article describes what the .NET Action<T> class is and how it can be used.

 

Action(T)

I recently discovered the Action in .NET.  It’s in version 4.0 of the .NET framework.  They’re very similar to delegates, but they require less setup.

Type Parameters

in T
The type of the parameter of the method that this delegate encapsulates. 

This type parameter is contravariant. That is, you can use either the type you specified or any type that is less derived. For more information about covariance and contravariance, see Covariance and Contravariance in Generics.

Parameters

obj
Type: T
The parameter of the method that this delegate encapsulates.

Click here for the complete definition with more examples from the MSDN Library.

Here’s an example:

    class ActionExample1
    {
        static void Main(string[] args)
        {
            List<String> names = new List<String>();
            names.Add("Bruce");
            names.Add("Alfred");
            names.Add("Tim");
            names.Add("Richard");

            // Display the contents of the list using the Print method.
            ShowOutput(names, Print);
        }

        private static void ShowOutput(List<String> argument, Action<string> action)
        {
            foreach (var arg in argument)
            {
                action(arg);
            };
        }

        private static void Print(string s)
        {
            Console.WriteLine(s);
        }
    }

Output:

You can also assign a lambda expression to an Action<T> delegate instance, as the following example illustrates.

    class ActionExampleLamda
    {
        static void Main3(string[] args)
        {
            Action<string> messageTarget;

            // Display the contents of the list using the Print method.
            messageTarget = s => Print(s);

            messageTarget("Hello World");
        }

        private static void Print(string s)
        {
            Console.WriteLine(s);
        }
    }

Here’s another example that utilizes the ForEach directly on the collection which takes an Action as an argument.

    class ActionExample2
    {
        static void Main2(string[] args)
        {
            List names = new List();
            names.Add("Bruce");
            names.Add("Alfred");
            names.Add("Tim");
            names.Add("Richard");

            // Display the contents of the list using the Print method.
            names.ForEach(Print);
        }

        private static void Print(string s)
        {
            Console.WriteLine(s);
        }
    }