A Better string.IsNullOrEmpty and more...
Submitted by brian on Sat, 06/20/2009 - 1:40am.
Here's a better version of string.IsNullOrEmpty(). Why is it better you say? Well my friend, this one checks the string for spaces... It also returns a positive statement (true if it is NOT null and NOT empty)
public static class Extensions { public static bool IsSafe(this string s) { return (s != null && s.Trim().Length > 0); } }
And some unit tests...
[Test] public void IsSafeStringTest() { string cheese = "is good"; Assert.IsTrue(cheese.IsSafe()); cheese = ""; Assert.IsFalse(cheese.IsSafe()); cheese = " "; Assert.IsFalse(cheese.IsSafe()); cheese = null; Assert.IsFalse(cheese.IsSafe()); //------------------------------- cheese = "yum"; Assert.IsFalse(string.IsNullOrEmpty(cheese)); cheese = ""; Assert.IsTrue(string.IsNullOrEmpty(cheese)); cheese = null; Assert.IsTrue(string.IsNullOrEmpty(cheese)); // rut roh... // string.IsNullOrEmpty() and spaces are not nice together. cheese = " "; // should be true! Assert.IsFalse(string.IsNullOrEmpty(cheese)); }
While the following might be nice, we know that we can't do it because of the null reference exception we might get (if cheese were to be null)...
string.IsNullOrEmpty(cheese.Trim());
Anyway, while we're doing some extension methods, here's a similarly named one I also use when working with generic lists.
public static bool IsSafe<T>(this List<T> t) { return (t != null && t.Count() > 0); }
And some unit tests...
Tags:
















