Check whether a string is empty in C#
This article illustrates the different techniques to check whether a string is empty in C#.
We should not use "" or String.Empty to check for empty strings in C#. This causes the string to compare with the empty string by using the Object.Equals() method, and will result in a CA1820 violation. To check for empty strings in C#, you can retrieve the string Length property and compare its value with 0, as illustrated below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
using System; public class Example { public static void Main() { string s = string.Empty; bool isEmpty = s.Length == 0; Console.WriteLine(isEmpty); // True } } |
The above solution uses string.Empty which doesn’t create any string object in the memory, whereas "" creates a new string object. Another option to check for empty strings in C# is string.IsNullOrEmpty() method. However, this will check the specified string with both null and empty string.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
using System; public class Example { public static void Main() { string s = string.Empty; bool IsNullOrEmpty = string.IsNullOrEmpty(s); Console.WriteLine(IsNullOrEmpty); // True } } |
Note that both Length == 0 comparison and String.IsNullOrEmpty() method performs faster than using Equals() method, which executes remarkably more MSIL instructions.
That’s all about checking whether a string is empty 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 :)