This post will discuss how to determine whether a string is empty or null in C#.

1. Using String.IsNullOrEmpty() method

The standard solution to determine whether a string is empty or null is using the String.IsNullOrEmpty() method. It returns true if the specified string is null or an empty string; otherwise, false.

Download  Run Code

2. Using or operator

Alternatively, we can use the or operator to determine whether a string is an empty string, or the string is null. The following sample illustrates its usage.

Download  Run Code

 
Starting with C# 9, you can use pattern matching for this. For example, the following code uses the alternate syntax for a null check with disjunctive or pattern.

Download  Run Code

3. Using String.IsNullOrWhiteSpace() method

Additionally, if you need to check for whitespace characters, use the String.IsNullOrWhiteSpace() method. It returns true if the specified string is null, empty, or consists only of white-space characters; otherwise, false.

Download  Run Code

That’s all about determining whether a string is empty or null in C#.