More string silliness

Lets convert that previous example into a C# 3.0 extension method.

It would be cool if we could add static extension methods instead.
IE: string.IsNullOrTrimmedEmpty();
rather than
x == null || x.IsTrimmedEmpty()

Test Class

using MbUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace YaddaYadda
{
class Program
{
public static bool IsNullOrTrimmedEmpty(string s)
{
return s == null || s.IsTrimmedEmpty();
}
static void Main(string[] args)
{
Assert.IsTrue(IsNullOrTrimmedEmpty(null));
Assert.IsTrue(IsNullOrTrimmedEmpty(“”));
Assert.IsTrue(IsNullOrTrimmedEmpty(” “));
Assert.IsFalse(IsNullOrTrimmedEmpty(” a “));
Assert.IsFalse(IsNullOrTrimmedEmpty(“a “));
Assert.IsFalse(IsNullOrTrimmedEmpty(” a”));
Assert.IsFalse(IsNullOrTrimmedEmpty(“a”));
Console.ReadLine();
}
}
}

The class with the extension method

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace YaddaYadda
{
public static class StringExtensions
{
public static bool IsTrimmedEmpty(this string s)
{
return s.Trim().Length == 0;
}

}
}

Advertisements

2 Responses to More string silliness

  1. Jay says:

    Someone asked, “why not do string.IsNullOrEmpty(x.Trim())”

    Because you can’t call null.Trim(). If x is null, you have a situation.

  2. Jay says:

    Someone asked, “why not do string.IsNullOrEmpty(x.Trim())”

    Because you can’t call null.Trim(). If x is null, you have a situation.

Leave a Reply

Please log in using one of these methods to post your comment:

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

%d bloggers like this: