What is the best way to check if a string is empty in C# in VS2005?
+12
A:
There's the builtin String.IsNullOrEmpty
which I'd use. It's described here.
ho1
2010-06-29 09:04:42
+1 for `String` instead of `string`. Similarly to `Int32.TryParse` instead of `int.TryParse`
abatishchev
2010-06-29 09:09:00
@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."
0xA3
2010-06-29 09:13:58
@0xA3: Undoubtedly. For me, first of all, this is just style of code
abatishchev
2010-06-29 09:33:21
+6
A:
try this one:
if (string.IsNullOrEmpty(YourStringVariable))
{
//TO Do
}
odiseh
2010-06-29 09:05:23
A:
The string.IsNullOrEmpty()
method on the string class itself.
You could use
string.Length == 0
but that will except if the string is null.
Dr Herbie
2010-06-29 09:06:30
+1
A:
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
2010-06-29 09:13:26
+1
A:
C# 4 has the String.IsNullOrWhiteSpace() method which will handle cases where your string is made up of whitespace ony.
ZombieSheep
2010-06-29 09:18:16
... which doesn't matter since it was asked for VS2005, i.e. .NET 2.0. Would have been a great comment though.
OregonGhost
2010-06-29 09:25:06
A:
ofc
bool isStringEmpty = string.IsNullOrEmpty("yourString");
Serkan Hekimoglu
2010-06-29 10:53:45