Checking for null is important in programming to avoid potential runtime errors, prevent crashes, and ensure the reliability and robustness of your code.

In C#, we can check for null in few different ways, depending on the context.

So far I have been using following methods:

  • Using the equality operator
1
2
3
4
5
6
7

object obj = null;

if (obj == null)
{
    // if null, do something
}
  • Using the is keyword
1
2
3
4
5
6
7

object obj = null;

if (obj is null)
{
    // if null, do something
}
  • Using the ReferenceEquals() method
1
2
3
4
5
6
7

object obj = null;

if (ReferenceEquals(obj, null))
{
    // if null, do something
}
  • Using the != opeartor
1
2
3
4
5
6
7

object obj = null;

if (obj != null)
{
    // object is not null
}
  • Using the null-conditional operator ?.
1
2
3

var text = null;
int? length = text?.Length; // length will be null, if text is null
  • Using the null-coalescing operator ??
1
2
3

var text = null;
var result = text ?? "default non-null value"; // if text is null, use the default value