The String
class in the System
namespace provides the IsNullOrEmpty()
method to check if a string is null or an empty string(""). This is a handy method to validate user input.
IsNullOrEmpty()
takes a string as an input and returns a Boolean value that depends on whether or not the string is null or empty.
public static bool IsNullOrEmpty (string? value);
The IsNullOrEmpty()
method returns true if the input is null
.
For example:
string str = null;
Console.WriteLine(String.IsNullOrEmpty(str)); //True
IsNullOrEmpty()
returns true if the input is an empty string. In C#, this is a zero length string ("").
For example:
string str1 = "";
string str2 = String.Empty;
Console.WriteLine(String.IsNullOrEmpty(str1)); // True
Console.WriteLine(String.IsNullOrEmpty(str2)); // True
The IsNullOrEmpty()
method can be used to avoid the null reference exception by checking if a string is null before using it, as seen below:
if(String.IsNullOrEmpty(userName)) {
//perform operation on string
}
In the example below, we call the IsNullOrEmpty()
method with different string inputs and print the result:
using System;class HelloWorld{static void Main(){string nullStr = null;// print TrueConsole.WriteLine(String.IsNullOrEmpty(nullStr));string emptyStr1 = "";// print TrueConsole.WriteLine(String.IsNullOrEmpty(emptyStr1));string emptyStr2 = String.Empty;// print TrueConsole.WriteLine(String.IsNullOrEmpty(emptyStr2));string str = "some text";// print FalseConsole.WriteLine(String.IsNullOrEmpty(str));}}