Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function as method call parameter

I have a simple question that might be easily answerd but an intense use of google didn't bring up an answer to my question. So I appologize if there's the right solution and I didn't see it.

If I have a method call like

Object.Add(string text, System.Drawing.Color color);

that is adding some text to some object with a specified color, and I want to dynamical change the color, then I can type sth. like

Object.Add("I'm a string", SomeBool ? Color.Red : Color.Green);

This is pretty helpful but will fail as soon as I want to compare more than just two cases.

What I'm looking for is something like (Pseudocode)

Object.Add("I'm another string", new delegate (Sytem.Drawing.Color) 
{
    if (tristate == state.state1) 
    {
        return Color.Blue;
    } 
    else if (tristate == state2)
    {
        return Color.Green;
    }
    // ...
});

But no matter what I'm trying it will throw an compiler error.

I tried a lot of google about how to pass a function as a method parameter but what I'll find is lot like

public void SomeFunction(Func<string, int> somefunction) 
{ 
    //... 
}

which is not my question.

Thank you :)

like image 657
AllDayPiano Avatar asked Mar 14 '23 03:03

AllDayPiano


1 Answers

Just place your logic first:

Color color;

if (tristate == state1) 
    color = Color.Blue;
else if (tristate == state2)
    color = Color.Green;
else
    color = Color.Red;

Object.Add("I'm a string", color);

The reason your delegate solution did not work is simply that new delegate (Sytem.Drawing.Color) { … } returns a function delegate which needs to be called first before you get a color value. And since your method requires a color and not a method that returns a color, it is not really helpful.

Depending on how short your logic is you could still use the ternary condition operator here and simply chain it:

Object.Add("I'm a string", tristate == state1 ? Color.Blue : tristate == state2 ? Color.Green : Color.Red);

This would be equivalent to the above verbose if/else if/else structure. But of course, it’s not necessarily more readable, so use with caution and choose the more readable solution.

like image 129
poke Avatar answered Mar 15 '23 17:03

poke