Question

In C# I know you can do things like this:

int number = true ? 1 : 0;

This returns the left or right side depending on if the Boolean is true or not.

But is there a way to do the same thing but instead run a function instead of returning a value? Something like this:

This doesn't work (I get multiple syntax errors)

WPS.EDIT_MODE ? ExecuteEditMode() : ExecutePublicMode();

Thanks.

Was it helpful?

Solution

The conditional operator must return a value. Assuming the functions don't both return a meaningful value for you, you should use an if statement to do that:

if(someCondition)
    doA();
else
    doB();

Although technically you could use an anonymous function to do this if you really wanted:

int number = someCondition ?
    new Func<int>(() => { doA(); return 0; })() :
    new Func<int>(() => { doB(); return 1; })();

but that's not suggested; using an if/else is both easier and more readable for that case.

OTHER TIPS

If both functions return an int, yes.

The ternary operator is about returning values. Not returning values doesn't make sense.

The conditional operator (?:) returns one of two values depending on the value of a Boolean expression.

http://msdn.microsoft.com/en-us/library/ty67wk28(v=vs.80).aspx

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top