0

Given the code below:

private static Dictionary<Type, Action<Control>> controlDefaults = new Dictionary<Type, Action<Control>>()
    {
        { typeof(TextBox), c => ((TextBox)c).Clear() }
    };

How would I invoke the action in this case? This is a code snippet taken from somewhere else, and the dictionary would contain many more instances of controls. This willbe used for resetting all controls on a form to their default values.

So would I iterate as such:

foreach (Control control in this.Controls)
{
    // Invoke action for each control
}

How would I then call the appropriate action from the dictionary for the current control?

Thanks.

abatishchev
  • 98,240
  • 88
  • 296
  • 433
Darren Young
  • 10,972
  • 36
  • 91
  • 150

3 Answers3

3

You can write

controlDefaults[control.GetType()](control);

You could also use a static generic class as the dictionary, and avoid casting:

static class ControlDefaults<T> where T : Control {
    public static Action<T> Action { get; internal set; }
}

static void Populate() {
    //This method should be called once, and should be in a different class
    ControlDefaults<TextBox>.Action = c => c.Clear();
}

However, you would not be able to call this in the loop, since you need to know the type at compile-time.

Community
  • 1
  • 1
SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
2

You invoke it like a function.

E.g.:

Action<Foo> action = foo => foo.Bar();
action(f);

So in your case:

foreach(Control control in this.Controls)
{
    controlDefaults[control.GetType()](control);
}
mdm
  • 12,480
  • 5
  • 34
  • 53
2
foreach (Control control in this.Controls)
{
    Action<Control> defaultAction = controlDefaults[control.GetType()];
    defaultAction(control);

    // or just
    controlDefaults[control.GetType()](control);
}
abatishchev
  • 98,240
  • 88
  • 296
  • 433