Uses of Action delegate in C#

122,721

Solution 1

MSDN says:

This delegate is used by the Array.ForEach method and the List.ForEach method to perform an action on each element of the array or list.

Except that, you can use it as a generic delegate that takes 1-3 parameters without returning any value.

Solution 2

Here is a small example that shows the usefulness of the Action delegate

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        Action<String> print = new Action<String>(Program.Print);

        List<String> names = new List<String> { "andrew", "nicole" };

        names.ForEach(print);

        Console.Read();
    }

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

Notice that the foreach method iterates the collection of names and executes the print method against each member of the collection. This a bit of a paradigm shift for us C# developers as we move towards a more functional style of programming. (For more info on the computer science behind it read this: http://en.wikipedia.org/wiki/Map_(higher-order_function).

Now if you are using C# 3 you can slick this up a bit with a lambda expression like so:

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        List<String> names = new List<String> { "andrew", "nicole" };

        names.ForEach(s => Console.WriteLine(s));

        Console.Read();
    }
}

Solution 3

Well one thing you could do is if you have a switch:

switch(SomeEnum)
{
  case SomeEnum.One:
      DoThings(someUser);
      break;
  case SomeEnum.Two:
      DoSomethingElse(someUser);
      break;
}

And with the might power of actions you can turn that switch into a dictionary:

Dictionary<SomeEnum, Action<User>> methodList = 
    new Dictionary<SomeEnum, Action<User>>()

methodList.Add(SomeEnum.One, DoSomething);
methodList.Add(SomeEnum.Two, DoSomethingElse); 

...

methodList[SomeEnum](someUser);

Or you could take this farther:

SomeOtherMethod(Action<User> someMethodToUse, User someUser)
{
    someMethodToUse(someUser);
}  

....

var neededMethod = methodList[SomeEnum];
SomeOtherMethod(neededMethod, someUser);

Just a couple of examples. Of course the more obvious use would be Linq extension methods.

Solution 4

You can use actions for short event handlers:

btnSubmit.Click += (sender, e) => MessageBox.Show("You clicked save!");

Solution 5

I used the action delegate like this in a project once:

private static Dictionary<Type, Action<Control>> controldefaults = new Dictionary<Type, Action<Control>>() { 
            {typeof(TextBox), c => ((TextBox)c).Clear()},
            {typeof(CheckBox), c => ((CheckBox)c).Checked = false},
            {typeof(ListBox), c => ((ListBox)c).Items.Clear()},
            {typeof(RadioButton), c => ((RadioButton)c).Checked = false},
            {typeof(GroupBox), c => ((GroupBox)c).Controls.ClearControls()},
            {typeof(Panel), c => ((Panel)c).Controls.ClearControls()}
    };

which all it does is store a action(method call) against a type of control so that you can clear all the controls on a form back to there defaults.

Share:
122,721
Biswanath
Author by

Biswanath

Einstein's theory implies that haskell cannot be faster than c

Updated on September 11, 2020

Comments

  • Biswanath
    Biswanath over 3 years

    I was working with the Action Delegates in C# in the hope of learning more about them and thinking where they might be useful.

    Has anybody used the Action Delegate, and if so why? or could you give some examples where it might be useful?

  • mackenir
    mackenir over 15 years
    I never noticed those multi-parameter versions of Action. Thanks.
  • Biswanath
    Biswanath over 15 years
    Nice, not a big deal of change but there is something called keyedbyTypeCollection, although I think it wraps around dictioinary(type, Object), may be.
  • Biswanath
    Biswanath over 15 years
    Great, I think this could be used as a decision table.
  • David Robbins
    David Robbins over 14 years
    Nice - this is a refactoring pattern "Replace Conditional with Polymorphism". refactoring.com/catalog/replaceConditionalWithPolymorphism.h‌​tml
  • surfmuggle
    surfmuggle almost 11 years
    Hi Sorskoot, could you expand how UpdateMethod, MyEventArgs and new BalieEventArgs are playing together. is the string Message passed into UpdateMethod: UpdateMethod("A Message")? Which method uses the object "someDataObject"? Thanks in advance
  • tdgtyugdyugdrugdr
    tdgtyugdyugdrugdr over 8 years
    You can use them for long ones too; btnSubmit.Click += (sender, e) => { MessageBox.Show("You clicked save!"); MessageBox.Show("You really did!"); };