How to Use string.IsNullOrEmpty in C# for Null or Empty Checks
Use
string.IsNullOrEmpty in C# to check if a string is either null or an empty string (""). It returns true if the string is null or empty, and false otherwise, helping you avoid errors when working with strings.Syntax
The string.IsNullOrEmpty method takes one string argument and returns a boolean value.
string.IsNullOrEmpty(value): Checks ifvalueisnullor empty ("").- Returns
trueifvalueisnullor empty. - Returns
falseifvaluecontains any characters.
csharp
bool result = string.IsNullOrEmpty(stringValue);
Example
This example shows how to use string.IsNullOrEmpty to check different strings and print whether they are null or empty.
csharp
using System; class Program { static void Main() { string nullString = null; string emptyString = ""; string normalString = "Hello"; Console.WriteLine(string.IsNullOrEmpty(nullString)); // True Console.WriteLine(string.IsNullOrEmpty(emptyString)); // True Console.WriteLine(string.IsNullOrEmpty(normalString)); // False } }
Output
True
True
False
Common Pitfalls
Some common mistakes when checking strings include:
- Using
== ""without checking fornull, which causes errors if the string isnull. - Confusing
string.IsNullOrEmptywithstring.IsNullOrWhiteSpace, which also checks for strings with only spaces.
Always use string.IsNullOrEmpty when you want to safely check for null or empty strings.
csharp
string s = null; // Wrong: throws exception if s is null // if (s == "") { ... } // Right: safe check if (string.IsNullOrEmpty(s)) { Console.WriteLine("String is null or empty"); }
Quick Reference
| Method | Description | Returns |
|---|---|---|
| string.IsNullOrEmpty(string value) | Checks if string is null or empty | true if null or empty, else false |
| string.IsNullOrWhiteSpace(string value) | Checks if string is null, empty, or whitespace only | true if null, empty, or whitespace, else false |
Key Takeaways
Use string.IsNullOrEmpty to safely check if a string is null or empty without errors.
It returns true for both null and empty strings, false otherwise.
Avoid using == "" alone because it throws errors if the string is null.
For checking spaces too, use string.IsNullOrWhiteSpace instead.
This method helps prevent common bugs when handling user input or data.