Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

string

c#

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

like image 347
CJ7 Avatar asked Jun 29 '10 09:06

CJ7


3 Answers

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

like image 112
Hans Olsson Avatar answered Nov 12 '22 08:11

Hans Olsson


try this one:

if (string.IsNullOrEmpty(YourStringVariable))
{
    //TO Do
}
like image 29
odiseh Avatar answered Nov 12 '22 09:11

odiseh


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
}
like image 2
Gertjan Avatar answered Nov 12 '22 08:11

Gertjan