How Can I Check Whether a String Variable Is Empty or Null in C#? [Duplicate]

How can I check whether a C# variable is an empty string "" or null?

I am looking for the simplest way to do this check. I have a variable that can be equal to "" or null. Is there a single function that can check if it's not "" or null?

1
if (string.IsNullOrEmpty(myString)) {
   //
}
7

Since .NET 2.0 you can use:

// Indicates whether the specified string is null or an Empty string.
string.IsNullOrEmpty(string value);

Additionally, since .NET 4.0 there's a new method that goes a bit farther:

// Indicates whether a specified string is null, empty, or consists only of white-space characters.
string.IsNullOrWhiteSpace(string value);

if the variable is a string

bool result = string.IsNullOrEmpty(variableToTest);

if you only have an object which may or may not contain a string then

bool result = string.IsNullOrEmpty(variableToTest as string);
2

string.IsNullOrEmpty is what you want.

if (string.IsNullOrEmpty(myString)) 
{
  . . .
  . . .
}

Cheap trick:

Convert.ToString((object)stringVar) == ""

This works because Convert.ToString(object) returns an empty string if object is null. Convert.ToString(string) returns null if string is null.

(Or, if you're using .NET 2.0 you could always using String.IsNullOrEmpty.)

2
Elena Rostova

Elena Rostova

Lead Health, Wellness & Medical Journalist

Elena Rostova holds a Master's degree in Public Health Journalism. She covers groundbreaking medical research, holistic wellness trends, mental health awareness, and nutritional science.

Share this article
Twitter Facebook Pinterest