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 classclass EmptyOrNullString{// main methodstatic void Main(){// create our stringsstring str1 = "Edpresso!";string str2 = "";// check if strings are empty// or nullbool str3 = string.IsNullOrEmpty(str1);bool str4 = string.IsNullOrEmpty(str2);// log out the returned valuesSystem.Console.WriteLine(str3);System.Console.WriteLine(str4);}}
Explanation
- The method returns
Trueforstr2because it is empty. - The method returns
Falseforstr1because it is not empty.