Extension method for is string whitespace, null or empty.

Here’s a quick extension method which returns true if string is whitespace, null or empty. I’ve also added

using Microsoft.VisualStudio.TestTools.UnitTesting;

public static class Extensions
{
    public static bool IsWhitespaceNullOrEmpty(this string s)
    {
        if (s == null) return true;
        if (s.Trim() == string.Empty) return true;
        return false;
    }
}

[TestClass]
public class UnitTest1
{
    [TestMethod]
    public void TestStringNull()
    {
        string s = null;
        Assert.IsTrue(s.IsWhitespaceNullOrEmpty());
        Assert.IsTrue(((string)null).IsWhitespaceNullOrEmpty());
    }

    [TestMethod]
    public void TestStringEmpty()
    {
        Assert.IsTrue(string.Empty.IsWhitespaceNullOrEmpty());
    }

    [TestMethod]
    public void TestSpaceStringEmpty()
    {
        Assert.IsTrue("    ".IsWhitespaceNullOrEmpty());
    }

    [TestMethod]
    public void TestTabStringEmpty()
    {
        Assert.IsTrue("\t".IsWhitespaceNullOrEmpty());
    }

    [TestMethod]
    public void TestStringNotEmpty()
    {
        Assert.IsTrue(!"a".IsWhitespaceNullOrEmpty());
    }
}
Advertisements

3 thoughts on “Extension method for is string whitespace, null or empty.

  1. Oh my goodness! Amazing article dude! Thank you, However I am having issues with
    your RSS. I don’t know the reason why I am unable to join it.

    Is there anybody else having the same RSS problems?
    Anyone who knows the solution can you kindly respond? Thanks!!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s