• Home
  • About
  •  

    Useful Extension Method On String

    June 30th, 2008

    .NET Framework provides String.IsNullOrEmpty() method which return true if the string is null or empty. It does not however take care of a string which only contains spaces. Often while persisting data we do not want to persist just empty strings. In past I have made this check before I let my data pass through. Today I thought of creating an extension method to do the same for me. Below is the code for the extension method which I have written in a StringExtensions class.

    public static class StringExtensions
    {
      public static bool IsNullOrEmptyWhenTrimmed(this string s)
      {
        return  !(s != null && s.Trim().Length > 0) ;
      }
    }

    Here is an example on how this extension method can be used.

    string x = "  ";
     
    if (x.IsNullOrEmptyWhenTrimmed())
      Console.WriteLine("String is empty or null");
    else
      Console.WriteLine("String is NOT empty or null");

    From now on I will be using this extension method whenever I have to check for empty strings. Short and sweet and useful :)

    kick it on DotNetKicks.com