Reputation: 23275
What is the best way to check if a string is empty in C# in VS2005?
Upvotes: 6
Views: 510
Reputation: 4284
ofc
bool isStringEmpty = string.IsNullOrEmpty("yourString");
Upvotes: 0
Reputation: 29953
C# 4 has the String.IsNullOrWhiteSpace() method which will handle cases where your string is made up of whitespace ony.
Upvotes: 1
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
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
Reputation: 26517
try this one:
if (string.IsNullOrEmpty(YourStringVariable))
{
//TO Do
}
Upvotes: 6
Reputation: 54999
There's the builtin String.IsNullOrEmpty
which I'd use. It's described here.
Upvotes: 13