Dealing With Null in C#
Dealing With Null in C#

Dealing with null is always a bit tricky and very error prone at beginner level. However, C#  provides a very clear documentation and implementation to make life easy.


What it is?

Null in C# refers to “nothing” or “invalid”. Often null gets mixed up with empty string, but an empty string refers to some existing value which is zero character long. It is very important to keep in mind the difference between value type and reference type in order to deal with null. From object oriented perspective, any reference type variable gets assigned with null by default which is not the case in terms of value types.By default, it is not  possible to assign null to a value type. For example, int number = null; will not compile. But, it is possible to make a value type nullable. The syntax to do this is as follows:

Nullable<int> number = null;

or in shorthand syntax

int? number = null;

On the other hand, converting a reference type to nullable is also not allowed. That’s why

string? text;

will also not compile because, string is a reference type and nullable by default.

Null Arithmetic

One of the key factor while dealing with null in conjunction with lifted operands (+, - , *, /, % etc) is that, the null propagates. For, example,

int? numberOne = 50;
int? numberTwo = 25;

var sum = numberOne + numberTwo; // 75
numberOne = null; // possible to assign null because, it is nullable int

sum = numberOne + numberTwo; // null

The easy interpretation to the above example is, if we add a number with “nothing” or “invalid” (numberOne = null;) the result will be nothing or something invalid. And if we use the value of sum in some other arithmetic calculation the result in those calculations will also be nothing or invalid.
However, nullable boolean works differently than any other value types. For example,

bool? x = null;
bool? y = true;
if (x == true || y == true) // though x is null, compiler will get inside the if clause as y is true
   var result = true;

Null Coalescing (??)

This operator produces the value of first expression if it is not null. If the first expression is null then it evaluates the second expression and produces the value of the second expression.;

string firstName = "Jahan";
string lastName = null;

var result = firstName + " " + (lastName ?? "[last name missing]")

In the line above, the result will be “Jahan [last name missing]” because, as the lastName is null (?? operator) will produce [last name missing] and concatenate with firstName. Be, very careful while null coalescing operator and always use it within parenthesis. Otherwise, weird result will be produced.

Null Conditional (?.)

Another very useful operator to deal with null is the null conditional operator (aka the elvis operator). What it does is, it checks the nullability of the receiver before calling or accessing the method or property.

string name = null;
int? result = name?.Length;

Notice, the result is a nullable int. And the reason is very simple. What we are saying is if the name is not null then give us the length of the name otherwise assign null to result. Now, we cannot assign null if the variable (result in this case) is not nullable. So,

string name = null;
int result = name?.Length;

Will produce compiler error.

Useful Tips

We know that, any instance method call will throw a null exception if the receiver is null. But this is not the case in terms of ToString() method call of nullable types.

int? number = null;
var result = number.ToString(); // result will be an empty string

There are a few very useful properties/methods available on any nullable types, such as

int? number = null;
number.HasValue // checks if there is any value
number.Value // gives the value that was assigned. Only use this property when you  are sure that there is a value. So, in conjunction with HasValue
number.GetValueOrDefault(); // assigns a default value if null is assigned. Zero in this case
number.GetValueOrDefault(77); // assigns a default value of your choice  if null is assigned. Zero in this case


January 2, 2018
Jahan Sarwar