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

Possible duplicate:
An easy way to write empty or empty?

I'm looking for the easiest way to check. I have a variable that can be equal to "or null. Is there only one function that can check if it is" "or null?

+43
c #
Nov 22 '11 at 9:40
source share
6 answers
if (string.IsNullOrEmpty(myString)) { // } 
+103
Nov 22 '11 at 9:41
source share

With .NET 2.0 you can use:

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

Also, since there is a new method in .NET 4.0 that goes a bit further:

 // Indicates whether a specified string is null, empty, or consists only of white-space characters. string.IsNullOrWhiteSpace(string value); 
+26
Nov 22 '11 at 9:45
source share

if the variable is a string

 bool result = string.IsNullOrEmpty(variableToTest); 

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

 bool result = string.IsNullOrEmpty(variableToTest as string); 
+6
Nov 22 '11 at 9:41
source share

Cheap trick:

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

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

(Or, if you are using .NET 2.0, you can always use String.IsNullOrEmpty.)

+1
Nov 22 2018-11-11T00: 00Z
source share

string.IsNullOrEmpty is what you want.

+1
Nov 22 2018-11-11T00: 00Z
source share
 if (string.IsNullOrEmpty(myString)) { . . . . . . } 
+1
Nov 22 '11 at 9:51
source share



All Articles