CJ7
CJ7

Reputation: 23275

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

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

Upvotes: 6

Views: 510

Answers (6)

Serkan Hekimoglu
Serkan Hekimoglu

Reputation: 4284

ofc

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

Upvotes: 0

ZombieSheep
ZombieSheep

Reputation: 29953

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

Upvotes: 1

Gertjan
Gertjan

Reputation: 880

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
}

Upvotes: 2

Dr Herbie
Dr Herbie

Reputation: 3940

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

You could use

string.Length == 0

but that will except if the string is null.

Upvotes: 0

odiseh
odiseh

Reputation: 26517

try this one:

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

Upvotes: 6

Hans Olsson
Hans Olsson

Reputation: 54999

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

Upvotes: 13

Related Questions