Jeff Key

It works on my machine

My Job

My stuff

Old stuff

Useful Stuff

Checking a string for null or empty string

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

Comments

Stefán Jökull Sigurðarson said:

What about the propably faster method (no casting going on):

(stringVar == null || stringVar.Length == 0)
# April 1, 2004 7:03 PM

Jeff Key said:

I wasn't suggesting the be-all-end-all check, but rather just another little trick. :) Yours should indeed be faster.

While Gooling something unrelated this morning I saw a question asking if there was anything like 2.0's IsNullOrEmpty, which prompted me to post this.
# April 1, 2004 8:12 PM

Stefán Jökull Sigurðarson said:

Yeah. I offered my method as an alternative. This is the beauty of programming, there is usually never just one correct way to do things. I guess it all comes down to habit and circumstances :)

Having looked at the CTP of Whidbey i can't wait to start using it in "day to day" programming. A quote i saw somewhere fits the occasion very well: "It sucks
to know the future when you're stuck in the present!"
# April 1, 2004 9:17 PM

Jeff Key said:

Too true! I find myself constantly running into situations where I could use the new language enhancements and the "refactoring" tools in the IDE will be a definite productivity enhancer. I've been using both C# Refactory (which seems to be out of business now) and the "C# Refactoring Tool" together for a while and it'll be great to have the stuff built into the IDE and solid, which neither tend to be at the moment.
# April 1, 2004 9:24 PM

JD said:

Jeff -

Do you have an URL for the "C# Refactoring Tool" you mention in the above post?

Also... I read somewhere (a MSFT blog entry, I think) that checking a string against "" was slow because the runtime needs to create a string object to hold the empty string.

if (myString == "")

The author suggested doing this instead:

if (myString == string.Empty)

No good for the null case, though, so I suppose that Stefan's initial post above is the way to go (for 1.1 anyway).

Cheers,

JD

# April 2, 2004 11:30 AM

Jeff Key said:

JD:

"C# Refactoring Tool": http://dotnetrefactoring.com/

Again, I was only showing a little-known trick..not the perfect or most performant solution, but simply the one that requires a single method call. (I've seen far too many people either do the null or empty string check, but forget to do both.) To be honest, I never use it because the stuff I write generally needs to be very fast. For things like transactional apps that don't require very high perf, it's more than adequate. (I just did a simple test on my laptop and it executed the line ~12,000,000 times in one second. There are certainly lower hanging perf fruit to worry about before this. :) )

..and I knew someone would would mention String.Empty! :) I've seen the argument a thousand times and it seems like definitive answer is always one or the other. Strings literals are interned, so the "" should only be created once. Check out the code below:

string a = "";
string b = a + a;
Console.WriteLine((object.ReferenceEquals("", String.Empty)).ToString());
Console.WriteLine((object.ReferenceEquals(b, String.Empty)).ToString());
Console.WriteLine((object.Equals(b, String.Empty)).ToString());

The result is True, False, True. The empty string literal and String.Empty point to the same object. The variable "b" is not interned and thus doesn't point to the same object.
# April 2, 2004 12:39 PM

JD said:

Cheers.. thanks!
# April 5, 2004 5:57 PM

Cornilius van Berkel said:

I find using paired Boolean conditions to test one state distracting, especially when they are used in a complex relational equation.
e.g.
if ((a != null && a != “”) && (b != null && b != “”) && etc)

I therefore make use of the function <b>String.Compare<b>.
e.g.
if ((String.Compare (a, “”) > 0) && (String.Compare (b, “”) > 0) && etc)
# May 2, 2004 7:42 AM

Zing said:

So does String.Compare work for nulls then? It says _nothing_ about that in the manual.
# May 24, 2004 9:48 PM

Jeff Key said:

A quick check shows that it does indeed work, but compares can be expensive if you're doing a lot of them.
# May 24, 2004 9:54 PM

Tony John said:

I have always preferred to kill 2 birds with 1 stone and so to make sure I catch both, null as well as not null empty strings, I do it like this:

// Append empty string to str, so if it was
// either null or empty string, the result
// would still be an empty string.
if ( (str + "").Length > 0 )
{
// Perform operations on not null or not
// empty string
}

The only caveat is that str+"" always creates a new string and so it needs to be used diligently. If the above expression is part of a loop, then the mutable StringBuilder class should be used to avoid unnecessary copies of str.
# July 8, 2004 7:58 PM

what is all the big deal with NullOrEmpty said:

Every application needs to have a util class

Just set up

public static bool IsNullOrEmpty(string stringVar)
bool b;
if(stringVar == null || stringVar.Length == 0)
{return b;}

and be done with it and stop whining about whidbey?

call it from anywhere:

if (!Util.IsNullOrEmpty(myString))
{myString="a good one"}

Isn't programming about creating stuff. Then why are all these "experienced" programmers begging to be spoon fed?

Rob
# July 19, 2004 10:56 AM

if ( (str + "").Length > 0 ) is the said:

this is the worst performance. It invovescreation of a string object and concatenation too.

Rob
# July 19, 2004 11:01 AM

Rob said:

Sorry got to typing too fast:

public static bool IsNullOrEmpty(String s)
{
bool b;
if (s == null || s == 0)
{
b=true;
}
return b;
}

rob
# July 19, 2004 11:11 AM

Raheel said:

you guys are awesome, i was stuck at the kinda prob cept i had an array. long story short i used arry[f] == null and it works like a charm

# December 1, 2006 10:55 PM

Steve said:

public static bool IsNullOrEmpty(string s)

{

return s == null || s.Length == 0;

}

# April 10, 2007 7:37 AM

Empty strings | Polymath Programmer said:

Pingback from  Empty strings | Polymath Programmer

# December 31, 2007 6:06 AM

Sunil.S said:

use  IsDBNull

dim str_empid as string

if  IsDBNull(str_empID) then

-------

-----

end if

# January 29, 2008 9:28 AM

Derek F. said:

Just ran across this but in .NET 2.0 how about the ?? shortcut.

string result = value1 ?? value2;

# February 11, 2008 6:14 AM

Jamie said:

I was writing a simple contact form which would send an email to a set address as if it was sent by the email which they entered. Of course some people might not want to enter there email address so a default one would be needed.

to do this I did something like this

string address = EmailBox.Text;

       if (String.IsNullOrEmpty(address))

           address = "me@me.com";

       mail.From = new MailAddress(address);

throws an error but works fine on a web server

# April 24, 2008 5:29 AM

collector said:

Its funny to see so many approaches for resolving so simple task :)

# May 29, 2008 12:09 PM

Timah said:

if (String.IsNullOrEmpty(TextBox1.Text))

       {

           Label1.Text = "Cha Cha Cha";

       }

       else

       {

           Label1.Text = "Moo Moo";

       }

or

if (String.IsNullOrEmpty(TextBox1.Text)  ==  true)

       {

           Label1.Text = "Cha Cha Cha";

       }

       else

       {

           Label1.Text = "Moo Moo";

       }

# January 20, 2009 3:42 AM

beer said:

I usually use first, Timah

# June 5, 2009 1:01 AM

anirudha.gandhe said:

too good. made my life easy.

# November 12, 2009 8:30 PM
Leave a Comment

(required) 

(required) 

(optional)

(required)