string.Reverse and C# 2.0 vs C# 3.0

I have been reading some Ruby tutorials and seen that Ruby has a Reverse method defined on string. Now I thought, why not create something like that for C#. My first idea was to add this to C# 2.0.

The first thing would be to create a static utility class (you can’t inherit from string in .NET) and implement a static Reverse method on it. Since I’m in C# 2.0 I’m thinking in a very procedural way.

Let’s have a look at the code:

/// <summary>
/// Utility class. Holding useful methods for System.String.
/// </summary>
public static class StringUtility
{
        /// <summary>
        /// Reverses the given string.
        /// </summary>
        /// <param name="value">String to reverse.</param>
        /// <returns></returns>
        public static string Reverse(string value)
        {
                if (value == null)
                        throw new ArgumentNullException(“value”);
                if (value.Length == 0)
                        return value;

                // Create the input and output array.
                char[] input = value.ToCharArray();
                char[] output = new char[value.Length];

                // Loop over the array and move the chars.
                for (int i = 0; i < input.Length; i++)
                {
                        output[input.Length - 1 - i] = input[i];
                }

                // Create the new output string.
                return new string(output);
        }
}

Now, how would that look like in C# 3.0? C# 3.0 adds some new functional sugar to the language. Internally C# creates delegates for the lambda expressions. These delegates are then invoked, as the code runs. The new version of the language adds also so called extension methods. Extension methods are defined in own classes and extend an existing class, struct or interface. If an extension method for string has been defined it shows up in intellisense, when you work with a string and the class defining it is in scope. The compiler is then translating the extension methods to normal method calls!

Defining an extension method is very easy. It only requires to put the this keyword as the first argument of the method. It signalizes that the extension method is defined for the following argument’s type.

Finally let’s have a look at the code:

/// <summary>
/// Class that holds the extensions for string.
/// </summary>
public static class StringExtensions
{
        /// <summary>
        /// Reverses the given string.
        /// </summary>
        /// <param name="value">String to reverse.</param>
        /// <returns></returns>
        public static string Reverse(this string value)
        {
                // Create the function definition.
                // This is required since we do a recursive call.
                Func<string, string> f = null;
                // Create the lambda expression.
                f = x => x.Length > 0 ? f(x.Substring(1)) + x[0] :
                         string.Empty;

                // Invoke it.
                return f(value);
        }
}

Wow! That’s shorter, isn’t it? The lambda expression is a little bit complexer, although it’s very easy, if you understand that the thing before the => is the argument of the function. Next follows a simple tenary operation: it makes clear that we exit when the whole string has been processed.

Published on May 4th, 2007 — Tags: ,
   digg it!    kick it   

10 Comments ( Comments RSS TrackBack )

  1. There’s a slightly easier way to do this in .Net 2.0:
    char[] chars = someString.ToCharArray();
    Array.Reverse(chars);
    string reversedString = new string(chars);

    Also, while your .Net 3.5 version is very elegant, I doubt it would be very performant because you’re creating a new String object with every call to Substring.

    All the same, it’s a nice illustration of the power of C# 3.0. Good first post. :)

    Comment by Sven Groot — May 4, 2007 @ 9:25 am

  2. Hey littleguru,
    You should check out this post about Extension methods: http://weblogs.asp.net/scottgu/archive/2007/03/13/new-orcas-language-feature-extension-methods.aspx.
    You could add an extension method to the string class. very cool.

    Comment by Cyonix — May 5, 2007 @ 6:20 pm

  3. Hi Cyonix,
    that’s what the second snippet (the C# 3.0 snippet) does. It adds an extension method to the string class.

    It’s used like that afterwards:

    string foo = “This is a test”;
    foo = foo.Reverse();

    Comment by Christian Liensberger — May 5, 2007 @ 6:41 pm

  4. Oops i didn’t see the (this string value) haha

    Cool blog :)

    Comment by Cyonix — May 5, 2007 @ 6:45 pm

  5. Cooooole Sache die Extension Methods.

    Obwohl diese Syntactic sugars den Code doch bissl komplexer machen, was dann f++r Wartung SEHR dagegen spricht.
    +£berhaupt wenn anderer Entwickler Wartung machen muss.

    Aber Beispiel ist SUPER!

    Comment by Peter — May 16, 2007 @ 9:36 am

  6. Hi fellow S++dtiroler :)

    OK maintainance is going to be harder with extension methods. But they are only methods and you can always press F12 when having the focus on a method to get the definition… This should make maintainance easier, shouldn’t it?

    The C# compiler translates the extension methods to a static method call during compile time. It’s nothing special that’s going on!

    PS: Could you please post in English to have all other readers understand your messages. Thanks!

    Comment by Christian Liensberger — May 17, 2007 @ 9:01 pm

  7. Hello! Good Site! Thanks you! iemsdxckjuyjlh

    Comment by blcxwmumxi — July 3, 2007 @ 4:35 pm

  8. Good example of lambda expression

    Comment by Ravi — February 20, 2009 @ 11:29 pm

  9. i wanr to create program of Reverse of string in asp.net 3.5

    i have two text box and button after click on button the first textbox string will reverse in second text box.

    i wrote these code

    string str1 =TextBox1.Text;
    string str2;
    int t =str1.Length;
    t–;
    int count=0;
    for (int i=t;i>=0;i–)
    {
    str2[count]=str1 [i];
    count++;
    }
    int t1 = str2.Length;
    str2 [t1]=”;
    TextBox2.Text = str2.ToString();

    Comment by Bhanu Pratap — December 15, 2009 @ 12:49 pm

  10. and earlier technologies, it’s remarkable article.

    Comment by noah detoxification machine — January 10, 2013 @ 2:38 am

Leave a comment

You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> [code][/code] [code lang="csharp"][/code].