C# Programming > Miscellaneous

C# ? Operator

Question-Mark Operator

A C# operator is symbols used as part of the C# syntax. For example, simple operators include <, >, &, |, etc. (Here is a complete list of C# operators).

An uncommon operator is the question-mark (?) operator. Basically, it is used to shorten if statements, which makes for elegant C# source code.

If vs ?

Consider the following example: there is a CheckBox and a Button. If the CheckBox is checked when the button is clicked, then we want the message "A" to appear. If the CheckBox isn't checked, then the message "B" appears.

The first way is to use an if statement:

if (checkBox1.Checked)
MessageBox.Show("A");
else
MessageBox.Show("B");

Now shorten the if statement with the ? C# operator:

MessageBox.Show(checkBox1.Checked ? "A": "B");

The structure for the ? operator comes out to:

condition ? [value for true] : [value for false]

The ? C# operator can help shorten parts of code to make it more compact and elegant. Don't let it scare you, it's just way to shorten conditionals.

Double Question Mark (??)

We can further shorten these statements with the C# double question mark operator. The double question mark operator is a shorthand for checking if an element is null.

Car myCar = (otherCar != null) ? otherCar : new otherCar();
Car myCar = otherCar ?? new otherCar(); //same thing

 

Back to C# Article List