In todays episode, I’ll show you how to use three advanced statements in C#. I’ll go over the so-called null-conditional operator, the null-coalescing operator and the ternary operator.

Null-Conditional Operator

You can use the null-conditional operator to prevent _NullReferenceException_s. The basic principle of the operator is to return a value if it is not null, and return null if it is. The following code shows you how to use the operator, which is initiated by a question mark, followed by a dot.

List<String> stringList = null;
int? val = stringList?.Count;

You can see the operator preceding the call of the Count-property. Running the code without the operator would lead to a NullReferenceException, but this way, null is assigned to the variable val instead.

Null-Coalescing Operator

The next operator is the null-coalescing operator. It is initiated by two question marks and it’s used to assign different values based on wether the first choice is null or not. To get a better understanding of this, let’s look at an example:

int? val = null;
int result = val ?? 0;

The value of the variable val is assigned to result. However, if val is equal to null, result will receive the value 0.

Ternary Operator

The last operator in todays article is the ternary operator. It basically provides a short hand version for if-else-statements that can be written in a single line.

Let’s look at the following example:

int val1 = 1;
int val2 = 2;
int smaller;

if (val1 > val2)
{
    smaller = val2;
}
else
{
    smaller = val1;
}

The if-statement takes up a lot of space while its logic is very simple. This can be replaced by the following code using the ternary operator:

int val1 = 1;
int val2 = 2;
int smaller = val1 > val2 ? val2 : val1;

By using the ternary operator, you can simplify the assignment of variable by typing an expression that returns either true or false after the assignment operator. Complete the statement by a question mark. After that, the two values separated by a colon represent the values that will be assigned to the variable. The first one will be used if the statement is true, otherwise the second one is assigned.