Action<> multiple parameters syntax clarification
Asked Answered
W

2

15

Sometimes I can't understand the simplest things, i'm sure it's in my face, i just fail to see it. Im trying to create a delegate for a method in this simple class:

public static class BalloonTip
{
    public static BalloonType BalType
    { 
        get; 
        set; 
    }

    public static void ShowBalloon(string message, BalloonType bType)
    {
        // notify user
    }
}

Now, this Action<> is supposed to create the delegate without actually declaring one with the keyword "delegate", did I understand correctly? Then:

private void NotifyUser(string message, BalloonTip.BalloonType ballType)
    {
        Action<string, BalloonTip.BalloonType> act; 
        act((message, ballType) => BalloonTip.ShowBalloon(message,  ballType));
    }

This fails to compile. Why?

(By the way, the reason why I need this delegate instead of directly calling ShowBalloon(), is that the calls must be made from another thread than the UI one, so I figured I need the Action<>)

Thanks,

Worser answered 23/6, 2012 at 18:50 Comment(1)
Action<> is nothing special, it is just a generic delegate (or Set of rather) Microsoft included in the "System" namespace on the .NET framework.Lacrosse
T
20

You need to first assign your anonymous method to the Action variable, then invoke it with the arguments passed in to the method:

private void NotifyUser(string message, BalloonTip.BalloonType ballType)
{
    Action<string, BalloonTip.BalloonType> act = 
        (m, b) => BalloonTip.ShowBalloon(m, b);

    act(message, ballType);
}

In this case, since the arguments expected by your Action variable are identical to those of the encapsulated method, you may also reference the method directly:

private void NotifyUser(string message, BalloonTip.BalloonType ballType)
{
    Action<string, BalloonTip.BalloonType> act = BalloonTip.ShowBalloon;

    act(message, ballType);
}
Thaler answered 23/6, 2012 at 18:57 Comment(1)
Thanks, I now finally understood how this Action is supposed to work and be used.Worser
R
2

Shouldn't you assign to the act variable? Something in the lines of:

Action<string, BalloonTip.BalloonType> act = BalloonTip.ShowBalloon;

Not only did you not assign a method to act, as it seems you are trying to invoke act passing it a anonymous method as a parameter, while it receives a string and a BalloonTip.BalloonType.
In the end, you should return act, and thus your method to get a delegate to the notification method should be:

public Action<string, BalloonTip.BalloonType> GetNotificationMethod() {
   Action<string, BalloonTip.BalloonType> act = BalloonTip.ShowBalloon;
   return act;
}  

You can also make it simpler:

public Action<string, BalloonTip.BalloonType> GetNotificationMethod() {
   return BalloonTip.ShowBalloon;
}  

Hope I understood your question ok. Good luck.

Risorgimento answered 23/6, 2012 at 19:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.