How to check if string is null or empty
In C#, use string.IsNullOrEmpty() to check if a string is null or has zero length. For checking null, empty, or whitespace-only strings, use string.IsNullOrWhiteSpace().
IsNullOrEmpty() returns true for null or "". IsNullOrWhiteSpace() also returns true for strings containing only spaces, tabs, or newlines.
These methods are safer than checking string.Length == 0 because they handle null values without throwing a NullReferenceException.
C# Example Code
using System;
public class CheckNullOrEmpty
{
public static void Main(string[] args)
{
// Test strings
string? nullString = null;
string emptyString = "";
string whitespaceString = " ";
string validString = "Hello";
// Using string.IsNullOrEmpty()
Console.WriteLine("IsNullOrEmpty:");
Console.WriteLine($" null: {string.IsNullOrEmpty(nullString)}"); // True
Console.WriteLine($" empty: {string.IsNullOrEmpty(emptyString)}"); // True
Console.WriteLine($" whitespace: {string.IsNullOrEmpty(whitespaceString)}"); // False
Console.WriteLine($" valid: {string.IsNullOrEmpty(validString)}"); // False
// Using string.IsNullOrWhiteSpace()
Console.WriteLine("\nIsNullOrWhiteSpace:");
Console.WriteLine($" null: {string.IsNullOrWhiteSpace(nullString)}"); // True
Console.WriteLine($" empty: {string.IsNullOrWhiteSpace(emptyString)}"); // True
Console.WriteLine($" whitespace: {string.IsNullOrWhiteSpace(whitespaceString)}"); // True
Console.WriteLine($" valid: {string.IsNullOrWhiteSpace(validString)}"); // False
// Practical usage in validation
string? userName = GetUserInput();
if (string.IsNullOrWhiteSpace(userName))
{
Console.WriteLine("\nError: Username cannot be empty");
}
else
{
Console.WriteLine($"Welcome, {userName}!");
}
// Using in conditional logic
string? email = "";
string displayEmail = string.IsNullOrEmpty(email) ? "No email provided" : email;
Console.WriteLine($"\nEmail: {displayEmail}");
// Multiple checks
string?[] inputs = { null, "", " ", "Valid" };
Console.WriteLine("\nValidating inputs:");
foreach (var input in inputs)
{
if (string.IsNullOrWhiteSpace(input))
{
Console.WriteLine($" '{input}' - Invalid");
}
else
{
Console.WriteLine($" '{input}' - Valid");
}
}
// Difference between the two methods
string spacesOnly = " ";
Console.WriteLine($"\nString with only spaces:");
Console.WriteLine($" IsNullOrEmpty: {string.IsNullOrEmpty(spacesOnly)}"); // False
Console.WriteLine($" IsNullOrWhiteSpace: {string.IsNullOrWhiteSpace(spacesOnly)}"); // True
}
static string? GetUserInput()
{
// Simulate user input
return ""; // Empty input
}
}