4

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
}
John Saunders
  • 160,644
  • 26
  • 247
  • 397
Jonathan D
  • 1,364
  • 2
  • 12
  • 30

7 Answers7

7

For strings, there is

if (String.IsNullOrEmpty(a))
C.Evenhuis
  • 25,996
  • 2
  • 58
  • 72
  • 2
    Better use String.IsNullOrEmpty() – HasanG May 25 '10 at 09:30
  • `string` beats `String` because you don't have to press shift, making your keyboard last longer, and makes you less tired, plus you don't need a `using System;` for the lowercase version. (kidding, applied and +1 for the correct capitalization when clearly accessing a static class method) – C.Evenhuis Dec 06 '11 at 09:19
3

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
  • 71,481
  • 13
  • 158
  • 186
  • 2
    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, but could be *much* faster than Count() for cases involving a complex query. http://danielvaughan.orpius.com/post/IEnumerable-IsNullOrEmpty.aspx – Janko R May 25 '10 at 10:01
3

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

Anemoia
  • 7,928
  • 7
  • 46
  • 71
1

From version 2.0 you can use IsNullOrEmpty.

string a;
...
if (string.IsNullOrEmpty(a)) ...
Patko
  • 4,365
  • 1
  • 32
  • 27
0

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
  • 125
  • 9
0
if(string.IsNullOrEmpty(string name))
{
   ///  write ur code
}
Johnny
  • 1,555
  • 3
  • 14
  • 23
0

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
  • 3,142
  • 2
  • 23
  • 32