For a while there, I would see mystical things happening in some code I viewed, and I had no idea what was happening - turn out the bla?bla:bla does mean something, and it is useful and simple
These?are:called ternary operators, and they can be very useful, especially when you want to clean up your code. A lot of people say that they are hard to read, but I think that is merely because they do not understand how simple they really are. I will show you just how simple they are; here is a statement using a ternary operator:
And all this means in simple terms is:
if a is true, then b is the value of the statement, else c is the value of the statement
or if you prefer code:
if(a)
return b;
else
return c;
That really is it, it is that simple. Ternary operators can save a lot of space, and more important (to me) they can easily be used inline, cutting out chunks of code completely. Take a look at the following for an example:
string s1 = "party";
string s2 = "crom";
string s3 = "arnold";
bool b1 = true;
bool b2 = false;
string s4, s5;
//All of this code:
if (b2)
s4 = s1;
else
s4 = s2;
if (b1)
s5 = s1;
else
s5 = s2;
//can be replaced by this
s4 = b2 ? s1 : s2;
s5 = b1 ? s1 : s2;
//plus you can easily use it inline
Response.Write("inline = " + (b2 ? s2 : s3).ToString());
You can make them much deeper and more complicated and then they may begin to get difficult to read, but for a lot of everyday tasks, ternary operators are great and space saving!