views:

365

answers:

4

With the ternary operator, it is possible to do something like the following (assuming Func1() and Func2() return an int:

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

However, is there any way to do the same thing, without returning a value? For example, something like (assuming Func1() and Func2() return void):

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

I realise this could be accomplished using an if statement, I just wondered if there was a way to do it like this.

A: 

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).

Lee
+2  A: 

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...

Daren Thomas
+4  A: 

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");
    }
}
Diego Pereyra
That's a lot of extra work to avoid just using "if" and "else". Nice snippet though.
GenericTypeTea
Yes. Nice snippet.
Ram
+1  A: 

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.

Erik Burigo