When you can use Conditional If Expression aka Single Line If Statement in .NET C#

… and the real name is ternary operator [thks pdh]…

I hope you know this way to write an if statement:

condition ? expression : expression

In .NET (hem and only c#) you can you this only as right operand such as:

a = (b > 50) ? 1 : 100;

you cannot use ?: to do something like this:

(b > 50) ? dothis() : dothat();

and hard to see, you cannot do this:

object a = (b > 50) ? "Hi There" : 999;

All expressions from right part have to return same type.

Keep in mind this is a great way to compact code, but somethimes it’s better think to keep code human readable.

VN:F [1.9.15_1155]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.15_1155]
Rating: 0 (from 0 votes)

2 Responses to “When you can use Conditional If Expression aka Single Line If Statement in .NET C#”

  1. pdh says:

    Please call it by its name, “Ternary operator”.

    VA:F [1.9.15_1155]
    Rating: 0.0/5 (0 votes cast)
    VA:F [1.9.15_1155]
    Rating: 0 (from 0 votes)
  2. admin says:

    You’re right, I’ve updated post. Thank you.
    …years ago, I didn’t like too much studying, I preferred to write brute force code, and the result is that I’m a good coder but I have sparse holes in my knowledge…

    VN:F [1.9.15_1155]
    Rating: 0.0/5 (0 votes cast)
    VN:F [1.9.15_1155]
    Rating: 0 (from 0 votes)

Leave a Reply