5

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

CJ7
  • 21,593
  • 63
  • 183
  • 312
  • 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
  • 53,038
  • 14
  • 91
  • 113
  • 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
  • 23,925
  • 32
  • 106
  • 150
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
  • 852
  • 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,135
  • 12
  • 65
  • 112
  • 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
  • 95,331
  • 80
  • 293
  • 426
Dr Herbie
  • 3,880
  • 1
  • 24
  • 27
0

ofc

bool isStringEmpty = string.IsNullOrEmpty("yourString");
abatishchev
  • 95,331
  • 80
  • 293
  • 426
Serkan Hekimoglu
  • 4,114
  • 5
  • 36
  • 62