String.IsNullOrBlank Extension Method

2019-02-06 05:28发布

I continuously check string fields to check if they are null or blank.

if(myString == null || myString.Trim().Length == 0)
{
    throw new ArgumentException("Blank strings cannot be handled.");
}

To save myself a bit of typing is it possible to create an extension method for the String class that would have the same effect? I understand how extension methods can be added for a class instance but what about adding a static extension method to a class?

if(String.IsNullOrBlank(myString))
{
    throw new ArgumentException("Blank strings cannot be handled.");
}

10条回答
对你真心纯属浪费
2楼-- · 2019-02-06 06:04
public static bool IsNull(this object o)
    {
        return string.IsNullOrEmpty(o.ToStr());
    }
    public static bool IsNotNull(this object o)
    {
        return !string.IsNullOrEmpty(o.ToStr());
    }
    public static string ToStr(this object o)
    {
        return o + "";
    }
查看更多
手持菜刀,她持情操
3楼-- · 2019-02-06 06:05

An overload to the existing answers could be:

public static bool IsNullOrBlank(this String text,Action<String> doWhat)
{
  if (text!=null && text.Trim().Length>0)
    doWhat(text);
}

Would be helpful if you only want to run code given a valid value.

Not a super useful example, but just showing the usage:

Name.IsNullOrBlank(name=>Console.WriteLine(name));
查看更多
\"骚年 ilove
4楼-- · 2019-02-06 06:07

You could do:

public static bool IsNullOrBlank(this String text)
{
  return text==null || text.Trim().Length==0;
}

And then call it like this:

if(myString.IsNullOrBlank())
{
  throw new ArgumentException("Blank strings cannot be handled.");
}

This works because C# allows you to call extension method on null instances.

查看更多
一夜七次
5楼-- · 2019-02-06 06:09

I know this is an old question but since it was bumped and it hasn't been mentioned already, as of .NET 4.0 you can simply use the String.IsNullOrWhiteSpace method to achieve the same result.

查看更多
登录 后发表回答