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.
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.
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:
The value of the variable val is assigned to result. However, if val is equal to null, result will receive the value 0.
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:
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:
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.
Subscribe via RSS