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

C#StringIsnullorempty

C# Problem Overview


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?

C# Solutions


Solution 1 - C#

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

Solution 2 - C#

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);

Solution 3 - C#

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);

Solution 4 - C#

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.)

Solution 5 - C#

string.IsNullOrEmpty is what you want.

Solution 6 - C#

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSamantha J T StarView Question on Stackoverflow
Solution 1 - C#oopbaseView Answer on Stackoverflow
Solution 2 - C#madd0View Answer on Stackoverflow
Solution 3 - C#jk.View Answer on Stackoverflow
Solution 4 - C#yrkView Answer on Stackoverflow
Solution 5 - C#cristobalitoView Answer on Stackoverflow
Solution 6 - C#AskerView Answer on Stackoverflow