Back to Home

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;

// 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
}

Take It Further

The C# Player's Guide book cover

The community's favorite C# guide — teaches every concept you just read about with clarity.

The C# Player's Guide — 5th Edition · RB Whitaker

Get it on Amazon →

As an Amazon Associate I earn from qualifying purchases.