Reversing a string using the Reverse Method in LINQ

A while back I wrote this post on how to use an extension method to reverse a string of text.  The method simply iterated each character in reverse order appending the character to a StringBuilder object, as shown below.

string oldstring = "England";
StringBuilder newString = new StringBuilder();
for (int i = oldString.Length - 1; i >= 0; i--)
{
    newString.Append(oldString[i]);
}

There is another way to reverse a string. Enter the LINQ Reverse method which “Inverts the order of the elements in a sequence” the keyword here is sequence. The result of calling the method is “A sequence whose elements correspond to those of the input sequence in reverse order.”
Again the word sequence. As a string object is s sequence of characters the result of the following statement

"Hello".Reverse();

will be IEnumerable, a sequence of characters because the method will see the input as a sequence of characters.
LINQ Reverse method in LINQPad
The desired output is to have a single string, so at this point we could iterate the sequence of characters using For loop and appending each character to a StringBuilder like in the previous example.

var oldString = "Hello".Reverse();
StringBuilder newString = new StringBuilder();
for (int i = 0; i < oldString.Length; i++)
{
    newString.Append(oldString[i]);
}

But I personally do not see any advantages in doing it this way as there will be additional processing from introducing the extra Reverse() method call.
What we can do here is use the string.Join method to concatenate the character sequence together. The signature of the Join method is string.Join(string, string[]). The first parameter is the separator which is only included in the returned string only if value has more than one element. The second parameter is an array that contains the elements to concatenate, Our sequence of characters needs to be somehow converted to an array.
So to reverse a string we need only a bit of extra LINQ and single line of code **drum roll please**

string.Join(string.Empty,
    "Hello".Reverse().Select(s => s.ToString()).ToArray())

Now, I am not recommending any one particular way. I have not compared memory or processor efficiencies between these techniques. What is plain is the difference in the number of lines required.

String Object Extension Methods

The C# Programming Guide describes extension methods as,

Extension methods enable you to “add” methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type. For client code written in C# and Visual Basic, there is no apparent difference between calling an extension method and the methods that are actually defined in a type.

Below are a couple of examples that extend the string object.  The first method reverses a string, functionality which appears to be missing from C#

public static String Reverse(this String oldString)
{
    StringBuilder newString = new StringBuilder();
    for (int i = oldString.Length - 1; i >= 0; i--)
    {
        newString.Append(oldString[i]);
    }
    return newString.ToString();
}

The next method uses regular expressions to replace characters in a string.

public static String Replace(this string originalString, string oldValue,
         string newValue, bool ignoreCase = false)
{
    Regex regEx = new Regex(oldValue,
        RegexOptions.IgnoreCase | RegexOptions.Multiline);
    if (ignoreCase)
    {
        regEx = new Regex(oldValue, RegexOptions.Multiline);
    }
    return regEx.Replace(originalString, newValue);
}

The type of the first parameter, which has the this keyword before it, defines what type of object is being extended. Normal this. notation can be used to reference properties of the extended object  from within the method.

To those of you familiar with SOLID principles the above description of extension methods will sound a lot like the Open-Closed principle (OCP).  This principle states that objects should be extendable without recompiling the application, modifying the original object or changing the existing behaviour of the object.  I agree to some degree that extensions methods do follow the OCP, though there is more to the principle than extending an object with static methods.  For now I will leave it to you to investigate  OCP further.