When you were a kid, did you ever ask your parents how to spell something and they told you to go look it up? My first impression was always, "well if could look it up I wouldnt need help spelling it". (yeah yeah I know phonetics)
...anyway, I was just looking at some code and I found an example like:
txtbx.CharacterCasing = (checkbox.Checked) ? CharacterCasing.Upper : CharacterCasing.Normal;
I can figure out what this operation does, but obviously, I cant google for ? or : and I cant find them when searching for "c# operators", LINQ, Lambda expressions, etc. So I have to ask this silly question so I can go start reading about it.
What are these operators?
?:
is the conditional operator, and the best way to find out is to ask here!
condition ? first_expression : second_expression;
If condition is true, first expression is evaluated and becomes the result; if false, the second expression is evaluated and becomes the result. Only one of two expressions is ever evaluated.
It's extremely helpful for readability of assignments, when the entire expression is relatively short:
string name = string.IsNullOrEmpty(user.Nickname) ? user.Fullname : user.Nickname
Is much easier and faster than:
string name = user.Fullname;
if(!string.IsNullOrEmpty(user.Nickname))
{
name = user.Nickname;
}
?
is an inline-if
statement. This means that if checkbox.Checked
is true
, then CharacterCasing.Upper
will be the value of the expression, otherwise CharacterCasing.Normal
will be.
It works like this:
type value = condition ? trueValue : falseValue;
that is an inline if statement. "?" is the code for the if, ":" is the for the else.
The ? is also known as the ternary operator
Incidentally, it so happens that you can search for "?:" on wikipedia and find this.
Note that it's also sometimes called "the" ternary operator, since its the only ternary (3-argument) operator in C-like languages.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With