How to check if a string has only whitespace or is empty in C#

Overview

In C#, the IsNullOrEmpty() method can be used to check if a string is empty or null. But if we want to check if a string is empty or just has whitespace, we can use the IsNullOrWhiteSpace() method.

The IsNullOrWhiteSpace() is used to indicate whether a specified string is empty, null, or contains only whitespace.

Syntax

string.IsNullOrWhiteSpace(str)

Parameters

str: The string we want to check if it’s empty, null, or contains only whitespace.

Return value

The function returns True if the string is actually empty, null, or contains only whitespace. Otherwise, the function returns False.

Example

In the code below, we’ll demonstrate the use of the IsNullOrWhiteSpace() method. We’ll create some strings with values and some with empty values. Then we’ll find out if they’re empty or not.

// create class
class WhiteSpaceChecker
{
// main method
static void Main()
{
// create strings
string str1 = "Educative.io";
string str2 = " ";
string str3 = "";
string str4 = " Edpresso ";
// check if they contain whitespaces or empty
bool a = string.IsNullOrWhiteSpace(str1);
bool b = string.IsNullOrWhiteSpace(str2);
bool c = string.IsNullOrWhiteSpace(str3);
bool d = string.IsNullOrWhiteSpace(str4);
// print out returne boolean values
System.Console.WriteLine(a);
System.Console.WriteLine(b);
System.Console.WriteLine(c);
System.Console.WriteLine(d);
}
}

Explanation

Line 2,3: str2 and str3 contain whitespace and are empty.

Line 14,15: str2 and str3 are checked with the IsNullOrEmpty() function and they return True.