SEO Friendly Strings, with a simple ToSeo() extension

In web development, you’ll spend a lot of time converting blog titles, image titles, page titles into SEO friendly format, ie:

iains-blogs-rock-my-world

In the past I would have written a static helper utility method to do this, eg

string convertMe = "Iain’s Blogs Rock My World";
string seoString = Utils.ConvertToSeo(convertMe);

However C# 3 gave us the awesome power of extension methods, which in the formal words of MSDN are:

Extension methods enable you to “add” methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type.

Or to put it another way, you can add methods to classes you didn’t write, be they classes in the framework or classes written by charlatans like my good self.

So we want to add a ToSeo() method onto the string object. To perform this black magic you must ensure the following is true:

  1. Your extension method must be static
  2. The first parameter specifies which type the method operates on, and the parameter must be preceded the this keyword
  3. The extension method must live in a public static class

So in our case we have

namespace HuzuSocial.Web.Helpers
{
    public static class Extensions
    {
        public static string ToSeo(this string str)
        {
            if (str == null)
                return null;
            else
            {
                // Remove any punctuation
                var sb = new StringBuilder();
                foreach (char c in str)
                {
                    if (!char.IsPunctuation(c))
                        sb.Append(c);
                }

                // Replace spaces with dashs and return
                return sb.ToString().ToLower().Replace(" ", "-");
            }
        }
    }
}

And now our new ToSeo() extension is available on all strings, as long as we have a reference to our extensions class

I think this is a definite improvement over the old utils class approach, and gives us a more flexible and natural way of adding functionality.

Advertisement