4 Apr
2007

Extension Methods Just Make Sense

Category:UncategorizedTag: , :

friend and colleague of mine has a favorite interview code problem that I think is pretty fun, too.  I think it is simpler than FizzBuzz, but is reasonably effective at prompting discussion.  The problem is quite simply, “Please go the whiteboard and reverse a string.”

I love the ambiguity of that problem.  Do you I get the string in a function? Do I assume I am within a function? Etc.  By the way, if you want an A+ from Matt, you should probably build a StringReverser object or something :).  Most candidates will answer with pseudo code, but curly brackets sprinkled in for art work, I guess.

Anyway, a typical implementation in C# might look something like this:

        static string ReverseString(string s1)
        {
            StringBuilder builder = new StringBuilder(s1.Length);
            for (int i = s1.Length-1; i >= 0; i--)
            {
                builder.Append(s1[i]);
            }
            return builder.ToString();
        }

The last time I watched a candidate write this answer on the board was just after Boise Code Camp and I had attended a great session on Ruby presented by Steve Borg from Accentient.  As a result of Steve’s Ruby session, I saw in my head that I wanted to add a .Reverse() function to the base string class.

Then, to my complete joy, Scott Guthrie posted about the extension methods that will be arriving in .Net later this year with the Orcas delivery.  With extension methods, a cleaner solution might look like this:

    public static class ECExtensions
    {
        public static string Reverse(this string s1)
        {
            StringBuilder builder = new StringBuilder(s1.Length);
            for (int i = s1.Length-1; i >= 0; i--)
            {
                builder.Append(s1[i]);
            }
            return builder.ToString();        
        }
    } 

After including the above class in my project, I can now simply do this (I think):

      return "foo".Reverse()

Thank you, .Net Language Extension Methods.  I think I got this right, but I don’t actually have a compiler that will syntax check me here.

3 thoughts on “Extension Methods Just Make Sense

  1. A friend of mine just hit me with your solution, Bill. This is cleaner, clearly.
    I was unaware of the Array.Reverse() function.

    The C# version looks like this.

    public static string Reverse(string input)
    {
    char[] inputChars = input.ToCharArray();
    Array.Reverse(inputChars);
    return new String(inputChars);
    }

Comments are closed.