How to check if a string value is empty or null in C#

Overview

A string value is said to be null or empty when the value has nothing. We can use the IsNullOrEmpty() method to check if a string is valueless. This method checks if a string is null or an empty string.

Syntax

public static bool IsNullOrEmpty(String str)

Parameters

  • str: The string to check if it is empty or not.

Return value

IsNullOrEmpty() returns True if the string is empty; otherwise, it returns False.

Example

In the code below, we demonstrate the use of the IsNullOrEmpty() method.

// create our class
class EmptyOrNullString
{
// main method
static void Main()
{
// create our strings
string str1 = "Edpresso!";
string str2 = "";
// check if strings are empty
// or null
bool str3 = string.IsNullOrEmpty(str1);
bool str4 = string.IsNullOrEmpty(str2);
// log out the returned values
System.Console.WriteLine(str3);
System.Console.WriteLine(str4);
}
}

Explanation

  • The method returns True for str2 because it is empty.
  • The method returns False for str1 because it is not empty.

Free Resources