Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Learning by example - terminology (?, :, etc)

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?

like image 671
Leroy Jenkins Avatar asked Oct 19 '09 19:10

Leroy Jenkins


5 Answers

?: 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;
}
like image 184
Rex M Avatar answered Nov 07 '22 07:11

Rex M


? 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;

like image 20
Adam Robinson Avatar answered Nov 07 '22 07:11

Adam Robinson


that is an inline if statement. "?" is the code for the if, ":" is the for the else.

like image 36
Ryan Alford Avatar answered Nov 07 '22 07:11

Ryan Alford


The ? is also known as the ternary operator

like image 2
Josh Mein Avatar answered Nov 07 '22 06:11

Josh Mein


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.

like image 1
Grumdrig Avatar answered Nov 07 '22 07:11

Grumdrig