C# patterns: checking if a string has a value after trimming

Posted: (EET/GMT+2)

 

You know the situation: you take user input, and want to make sure there is something in the input given: real text instead of null values, empty strings or just spaces.

Trimming out spaces is trivial with the Trim() method of any string variable, but the problem is that if the string value is null, you get an NullReferenceException with the message, "Object reference not set to an instance of an object".

Of course, you can use the string.IsNullOrEmpty or string.IsNullOrWhiteSpace, but the problem is that if you want to check *if data exists*, then you have to negate: "not null". This is somewhat counter-intuitive in my opinion (your mileage might vary). This is how this would look in C#, I'm sure you have seen and used this before:

if (!string.IsNullOrWhiteSpace(input))
{
}

Instead of this code, I'd much rather say, "if this string has a meaningful value", then do something. In C#:

if (input.HasContent())
{
}

Now, how would you implement this said HasContent method? In my opinion, the easiest way is to create an extension method. The virtue of extension methods is that they also work with null objects, instead of regular instance methods. Besides, the String class is sealed, so you cannot inherit from it; on the other hand, extension method implementations are static methods.

Here's my take on this:

public static class StringHelpers
{
  public static bool HasContent(this string value)
  {
    if (value == null) return false;
    bool dataAfterTrim = (value.Trim() != "");
    return dataAfterTrim;
  }
}

Hope this helps!