C# - How to Reverse a Unicode String


Perhaps due to the lack of a built-in String.Reverse method in the .NET Framework, it's very common for implementations of such a method to be posted.
Unfortunately, most of these implementations do not handle characters outside Unicode's Basic Multilingual Plane correctly. These supplementary characters have code points between U+10000 and U+10FFFF and so cannot be represented with one 16-bit char. In UTF-16 (which is how .NET strings are encoded), these Unicode characters are represented as two C# chars, a high surrogatefollowed by a low surrogate. When the string is reversed, the order of these two chars has to be preserved.
Here's our method that reverses a string while handling surrogate code units correctly:

C# - How to Reverse a String

Unfortunately, C#'s string class is missing a Reverse() function, so here are three ways to reverse strings:

1. Manual Reversal

The most obvious way is to reverse a string by manually walking through it character for character and building a new string:

string input = "hello world";
string output = "";
for (int i = input.Length - 1; i >= 0; i--)
{
    output += input[i];
}
Note that if you take this approach in a serious program, you should use StringBuilder instead of string, since in the above code, a new temporary string is created each time you add a single character to the output string.

C# - Booleans Without Short-Circuiting

C# implements the boolean AND and OR operations like C/C++ with the operators && and ||.
The 'single character' versions of these (& and |) are used in both languages for bitwise AND and OR operations.
But in C# the single character versions can be used for boolean logic too, but with a twist.
The standard boolean operators (&& and ||) try to make your code as efficient as possible, by employing short-circuiting, to skip evaluation where possible.
If we have a boolean AND expression with two arguments, we know that the expression as a whole is false if one (or both) of the arguments is false. Thus when the first argument is false, the end result is known, and the second argument is never evaluated.
With OR it's the other way around: if one argument is true, the whole expression is true. Thus if the first argument evaluates to true, the second argument isn't evaluated.
Consider this sample class:

C# - Efficiently Looping Over An Array

This tip can improve the speed of programs that spend a lot of time looping over arrays.

Propably you know from experience, that when you try to access an invalid array element (say, index 11 in an array of size 10) you will get an IndexOutOfRangeException. To be able to generate this exception and prohibit the dangerous access of memory beyond your array storage, the runtime performs an array bounds check everytime you access an array, which checks that the index you supply is lower then the array size.
For example, take a look at this code: