tags:

views:

169

answers:

6

What is the best way to check if a string is empty in C# in VS2005?

+12  A: 

There's the builtin String.IsNullOrEmpty which I'd use. It's described here.

ho1
+1 for `String` instead of `string`. Similarly to `Int32.TryParse` instead of `int.TryParse`
abatishchev
@abatishchev: Note that there is no semantical difference between those two. Jon Skeet explained quite well when it makes sense to use each of the variants: http://stackoverflow.com/questions/215255/string-vs-string-in-c/215422#215422. In fact, the C# spec states: "As a matter of style, use of the keyword is favored over use of the complete system type name."
0xA3
@0xA3: Undoubtedly. For me, first of all, this is just style of code
abatishchev
+6  A: 

try this one:

if (string.IsNullOrEmpty(YourStringVariable))
{
    //TO Do
}
odiseh
A: 

The string.IsNullOrEmpty() method on the string class itself.

You could use

string.Length == 0

but that will except if the string is null.

Dr Herbie
+1  A: 

As suggested above you can use String.IsNullOrEmpty, but that will not work if you also want to check for strings with only spaces (some users place a space when a field is required). In that case you can use:

if(String.IsNullOrEmpty(str) || str.Trim().Length == 0) {
  // String was empty or whitespaced
}
Gertjan
+1  A: 

C# 4 has the String.IsNullOrWhiteSpace() method which will handle cases where your string is made up of whitespace ony.

ZombieSheep
... which doesn't matter since it was asked for VS2005, i.e. .NET 2.0. Would have been a great comment though.
OregonGhost
A: 

ofc

bool isStringEmpty = string.IsNullOrEmpty("yourString");
Serkan Hekimoglu