开发者

Null and blank values

开发者 https://www.devze.com 2022-12-31 07:01 出处:网络
What\'s the best way of writi开发者_StackOverflow社区ng robust code so that a variable can be checked for null and blank.

What's the best way of writi开发者_StackOverflow社区ng 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
}


For strings, there is

if (String.IsNullOrEmpty(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.


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


From version 2.0 you can use IsNullOrEmpty.

string a;
...
if (string.IsNullOrEmpty(a)) ...


if(string.IsNullOrEmpty(string name))
{
   ///  write ur code
}


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
}


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号