Ternary operators in C#

戏子无情 提交于 2019-11-29 04:04:34

Weird, but you could do

class Program
{
    private delegate void F();

    static void Main(string[] args)
    {
        ((1 == 1) ? new F(f1) : new F(f2))();
    }

    static void f1()
    {
        Console.WriteLine("1");
    }

    static void f2()
    { 
        Console.WriteLine("2");
    }
}

I don't think so. As far as I remember, the ternary operator is used in an expression context and not as a statement. The compiler needs to know the type for the expression and void is not really a type.

You could try to define a function for this:

void iif(bool condition, Action a, Action b)
{
    if (condition) a(); else b();
}

And then you could call it like this:

iif(x > y, Func1, Func2);

But this does not really make your code any clearer...

If you feel confident, you'd create a static method whose only purpose is to absorb the expression and "make it" a statement.

public static class Extension
{
    public static void Do(this Object x) { }
}

In this way you could call the ternary operator and invoke the extension method on it.

((x == y) ? Func1() : Func2()).Do(); 

Or, in an almost equivalent way, writing a static method (if the class when you want to use this "shortcut" is limited).

private static void Do(object item){ }

... and calling it in this way

Do((x == y) ? Func1() : Func2());

However I strongly reccomend to not use this "shortcut" for same reasons already made explicit by the authors before me.

No, because the ternary operator is an expression, whereas actions/void functions are statements. You could make them return object, but I think that an if/else block would make the intent much clearer (i.e. the actions are being executed for their side-effects instead of their values).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!