My favorite System.String extension methods

Posted by – September 27, 2009

.NET LogoEach business applications developer spends a lot of the time working with strings. Strings are everywhere and we do not avoid that, but we can make our life simpler. How many times each day do you use String.Format(), String.Trim() or String.IsNullOrEmpty()? This are of course very helpful method but turned out that in my case they do not provide a functionality I require. I found out that almost all the time I am treating null, an empty string and a string with whitespaces only as the same “undefined/unkown” value. I am doing that mostly with strings received from outside of my applications where I an interested in “real values” instead of for instance a string with spaces only. In this case, methods mentioned above do not meet my needs. Because of that I have created replacement for them as an extension methods and they became my favorite tools to work with strings (I am using them everywhere instead of out of the box methods).

StringExtensions class defining extension methods:

using System;

namespace ByteCarrot.Shared.Infrastructure
{
    public static class StringExtensions
    {
        public static string NullTrim(this string s)
        {
            if (s == null)
            {
                return null;
            }

            s = s.Trim();
            return s == String.Empty ? null : s;
        }

        public static bool IsSet(this string s)
        {
            return s.NullTrim() != null;
        }

        public static string AsFormat(
            this string s, params object[] args)
        {
            return String.Format(s, args);
        }
    }
}

IsSet() extension method – returns true only if string contains at least one “printable” character:

if (!this.Commands.IsSet())
{
    this.Logger.LogError("Commands not specified.");
}

NullTrim() extension method – returns string trimmed from both sides and null when base string was null or after trimming turned out that output is an empty string:

var commands = this.Commands.NullTrim();

AsFormat() extension method – shorter replacement for System.String:

Resources.RequiredField.AsFormat("First name");

It is nothing fancy but make my life easier.

Hey, keep in touch!! Follow me on Twitter, @marcinobel or subscribe to this blog.
0 Comments on My favorite System.String extension methods

Respond | Trackback

Respond

Comments

Comments