Wednesday, February 6, 2008

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;
}

}
}

1 comment:

Anonymous said...

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

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