How to Check if String is Null or Empty in C#
In C#, use
string.IsNullOrEmpty(yourString) to check if a string is either null or empty (""). This method returns true if the string has no value or is empty, otherwise false.Syntax
The method string.IsNullOrEmpty takes one string argument and returns a boolean value.
string.IsNullOrEmpty(value): Returnstrueifvalueisnullor an empty string ("").- Returns
falseifvaluecontains any characters.
csharp
bool result = string.IsNullOrEmpty(yourString);
Example
This example shows how to use string.IsNullOrEmpty to check different string values and print the results.
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 can cause errors. - Confusing
string.IsNullOrEmptywithstring.IsNullOrWhiteSpace, which also checks for spaces.
Always use string.IsNullOrEmpty to safely check for null or empty strings.
csharp
string s = null; // Wrong: This does NOT throw an exception if s is null // bool isEmpty = (s == ""); // Right: Safe check for null or empty bool isEmpty = string.IsNullOrEmpty(s);
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.
Avoid comparing strings to "" without checking for null first.
string.IsNullOrWhiteSpace also checks for spaces and tabs, use when needed.
This method helps prevent errors from null string references.
It returns a simple true or false, making code clean and readable.