views:

134

answers:

7

What's the best way of writing robust code so that a variable can be checked for null and blank.

e.g.

string a;

if((a != null) && (a.Length() > 0))
{
    //do some thing with a
}
+7  A: 

For strings, there is

if (string.IsNullOrEmpty(a))
deltreme
Better use String.IsNullOrEmpty()
HasanGursoy
+1  A: 

From version 2.0 you can use IsNullOrEmpty.

string a;
...
if (string.IsNullOrEmpty(a)) ...
Patko
A: 

for strings:

string a;
if(!String.IsNullOrEmpty(a))
{
//do something with a
}

for specific types you could create an extention method note that i've used HasValue instead of IsNullorEmpty because 99% of the times you will have to use the !-operator if you use IsNullOrEmpty which I find quite unreadable

public static bool HasValue(this MyType value)
{
//do some testing to see if your specific type is considered filled
}
Sander
+3  A: 

You can define an extension method to allow you to do this on many things:

static public bool IsNullOrEmpty<T>(this IEnumerable <T>input)
{
    return input == null || input.Count() == 0;
}

It already exists as a static method on the System.String class for strings, as has been pointed out.

David M
quoting John Skeet:However, you should definitely use Any(). That way it only needs to test for the presence of the first element. This will be incredibly cheap for normal implementations of ICollection<T>, but could be *much* faster than Count() for cases involving a complex query.http://danielvaughan.orpius.com/post/IEnumerable-IsNullOrEmpty.aspx
Janko R
+3  A: 

And if you are using .NET 4.0 you might want to take a look at String.IsNullOrWhiteSpace.

Snake
A: 
if(string.IsNullOrEmpty(string name))
{
   ///  write ur code
}
Johnny
A: 

I find Apache Commons.Lang StringUtils (Java)'s naming a lot easier: isEmpty() checks for null or empty string, isBlank() checks for null, empty string, or whitespace-only. isNullOrEmpty might be more descriptive, but empty and null is, in most cases you use it, the same thing.

Cthulhu