5

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

CJ7
  • 22,579
  • 65
  • 193
  • 321
  • 3
    Fantastic. 5 nearly identical answers within minutes of the posting of what is arguably the simplest C# question in SO history. Covered in meta; http://meta.stackexchange.com/questions/114/noob-questions-simple-answers-and-big-rep-points – xcud Jun 29 '10 at 13:00

6 Answers6

12

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

Hans Olsson
  • 54,199
  • 15
  • 94
  • 116
  • 1
    +1 for `String` instead of `string`. Similarly to `Int32.TryParse` instead of `int.TryParse` – abatishchev Jun 29 '10 at 09:09
  • 4
    @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." – Dirk Vollmar Jun 29 '10 at 09:13
  • @0xA3: Undoubtedly. For me, first of all, this is just style of code – abatishchev Jun 29 '10 at 09:33
6

try this one:

if (string.IsNullOrEmpty(YourStringVariable))
{
    //TO Do
}
odiseh
  • 25,407
  • 33
  • 108
  • 151
2

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
  • 850
  • 6
  • 9
1

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

ZombieSheep
  • 29,603
  • 12
  • 67
  • 114
  • 1
    ... which doesn't matter since it was asked for VS2005, i.e. .NET 2.0. Would have been a great comment though. – OregonGhost Jun 29 '10 at 09:25
0

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

You could use

string.Length == 0

but that will except if the string is null.

abatishchev
  • 98,240
  • 88
  • 296
  • 433
Dr Herbie
  • 3,930
  • 1
  • 25
  • 28
0

ofc

bool isStringEmpty = string.IsNullOrEmpty("yourString");
abatishchev
  • 98,240
  • 88
  • 296
  • 433
Serkan Hekimoglu
  • 4,234
  • 5
  • 40
  • 64