Wednesday, August 8, 2012

C# Extension Method to Reverse a String

Someone recently asked me to write some quick code to writing a reversed string to the console.  What I came up with at the time was this:

string s = "abcdefg";
foreach (char c in s.Reverse())
    Console.Write(c);


The string class has a Reverse method on it already, but it returns an IEnumerable, not the reversed string. 

After the fact, I looked at other ways of doing it and figured out a one-liner:

Console.WriteLine(String.Join("", s.ToCharArray().Reverse<char>()));

Going a step further (since I wanted to experiment a little with extension methods), I wrote this little string class extension method to encapsulate that functionality as follows:

public static class StringExtensions{
    public static string ReverseString(this string s)
    {
        return String.Join("", s.ToCharArray().Reverse<char>());
    }
}


Now I can simply write:

string s = "abcdefg";
Console.WriteLine(s.ReverseString());


The whole console program is as follows:

using System;
using System.Linq;


namespace ConsoleApplication1
{
    public static class StringExtensions
    {
        public static string ReverseString(this string s)
        {
            return String.Join("", s.ToCharArray().Reverse<char>());
        }
    }


    class Program
    {
        static void Main(string[] args)
        {
            string s = "abcdefg";
            Console.WriteLine(s.ReverseString());
            Console.ReadLine();
        }
    }
}


And since ReverseString is a an extension method extending the Framework string class, it shows up in intellisense like this as if it were a static method on the string class itself.  The down arrow indicates it's an extension method (among many already defined on string).