Case study - terminology (?,:, Etc.)

When you were a child, did you ever ask your parents how to write something, and they told you to go see? My first impression was always: "Well, if I could find him, I would not need help writing." (yes, I know phonetics)

... Anyway, I was just looking at some kind of code, and I found an example like:

 txtbx.CharacterCasing = (checkbox.Checked) ? CharacterCasing.Upper : CharacterCasing.Normal;

I can understand what this operation does, but obviously I can’t use Google? or: and I cannot find them when searching for "C # operators", LINQ, lambda expressions, etc. So I have to ask this stupid question to start reading about it.

What are these operators?

+5
source share
6 answers

?:is a conditional statement , and the best way to find out is to ask here!

condition ? first_expression : second_expression;

If the condition is true, the first expression is evaluated and becomes the result; if false, the second expression evaluates and becomes the result. Only one of the two expressions is evaluated.

This is extremely useful for readability of assignments when the whole expression is relatively short:

string name = string.IsNullOrEmpty(user.Nickname) ? user.Fullname : user.Nickname

It is much simpler and faster than:

string name = user.Fullname;
if(!string.IsNullOrEmpty(user.Nickname))
{
    name = user.Nickname;
}
+18
source

?is an inline- operator if. This means that if checkbox.Checked true, then it CharacterCasing.Upperwill be the value of the expression, otherwise it CharacterCasing.Normalwill.

It works as follows:

type value = condition ? trueValue : falseValue;

+5
source

inline if. "?" if, ":" else.

+3

?

+2
source

By the way, it so happened that you can find "?:" On Wikipedia and find it.

Note that it is also sometimes called the β€œtriple” operator, since its only ternary (3-argument) operator is in C-like languages.

+1
source

Btw. When you learn C #, check ?? operator . Is an alternative sometimes better?:.

Consider:

Console.WriteLine(user.LastName ?? "no last name provided");

vs

Console.WriteLine(user.LastName != null ? user.LastName : "no last name provided");
+1
source

All Articles