Determine whether a string is empty or null in C#
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
using System; public class Example { public static void Main() { string s = ""; if (string.IsNullOrEmpty(s)) { Console.WriteLine("String is either empty or null"); } } } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
using System; public class Example { public static void Main() { string s = ""; if (s == null || s == "") { Console.WriteLine("String is null or empty"); } } } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
using System; public class Example { public static void Main() { string s = ""; if (s is null or "") { Console.WriteLine("String is either empty or null"); } } } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
using System; public class Example { public static void Main() { string s = " "; if (string.IsNullOrWhiteSpace(s)) { Console.WriteLine("String is null, empty, or consist of only whitespaces"); } } } |
That’s all about determining whether a string is empty or null in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)