Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String.IsNullOrBlank Extension Method

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.");
}
like image 643
sipsorcery Avatar asked Mar 15 '09 11:03

sipsorcery


1 Answers

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.

like image 163
Sean Avatar answered Oct 10 '22 20:10

Sean