C# Reverse Extension Method

This C# example program uses the Reverse extension method. It requires System.Linq.
Reverse. Elements can be reversed in many ways. One way applies the Reverse extension method for a declarative, clear syntax. The Reverse method acts upon many collection types.
With this extension method, we receive the elements in the opposite order. Reverse can be used on lists, arrays and IEnumerable things. It is useful, but not perfect.
First, we show how to invoke the Reverse extension method from the System.Linq namespace. The program includes the System.Linq namespace at the top. This is important.LINQ

Tip: The Reverse extension method is not defined on the array type. It is an extension, not instance, method.

LINQ: It is defined in the LINQ library and can act upon arrays. This program writes the opposite element order in the array to the screen.

C# program that uses Reverse extension method using System; using System.Linq; class Program { static void Main() { // Create an array. int[] array = { 1, 2, 4 }; // Call reverse extension method on the array. var reverse = array.Reverse(); // Write contents of array to screen. foreach (int value in reverse) { Console.WriteLine(value); } } } Output 4 2 1
Performance notes. The Reverse extension method will likely have worse performance in many cases than other methods. This is because there is an iterator used in the LINQ method.

Allocations: LINQ requires more allocations and in the end results in worse performance.

Array.Reverse. To achieve better performance, it would be possible to use the Array.Reverse method, or even use imperative statements and loops.Array.ReverseArray

Also: Typically, LINQ methods will degrade performance on low-level value type collections.

A review. The Reverse extension method is effective. But it may not be ideal for all programs. The declarative, function-based syntax of Reverse is short but not optimally fast.
© 2007-2019 Sam Allen. Every person is special and unique. Send bug reports to
Dot Net Perls