Home | Contact Us

CSharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript

C# Foreach Reverse Loop

This C# program shows the foreach loop used with a Reverse extension method call.

Foreach reverse loop. How can you reverse a foreach-loop?

We can use a foreach-loop over a collection in the reverse order. The keyword foreach is useful making loops simpler and less prone to bugs But it has no obvious way to go backwards.

Example. First, you can't use a foreach-loop in the reverse direction over every collection, as some collections are generated as you go along. However, many collections, IEnumerable ones, can.

Tip: There is a Reverse<T>() method that "inverts" the order of elements in an IEnumerable collection.


C# program that uses Reverse

using System;
using System.Linq;

class Program
    static void Main()
	// Example string array
	string[] arr = new string[]
	// 1
	// Use the Reverse generic extension method.
	// Note how <string> is specified before the params.
	foreach (string s in arr.Reverse<string>())
	// 2
	// Use the Reverse generic extension method,
	// but omit the <string> part. This is sometimes OK.
	foreach (string s in arr.Reverse())

    Output is repeated twice.


Reverse is an extension method, meaning it is really a static method that uses special syntax like an instance method. It receives an IEnumerable collection, which includes arrays (string[]) and Lists.

Extension MethodStatic Method

Note: In part 1 above, we specify <string> before the parameter list for Reverse. We want the Reverse method that acts on strings.

Also, for some collections that implement their own Reverse method, you need to specify the <string> to indicate you want the extension method, not the regular one. This method is slower than using reverse iteration on a for-loop.


Tip: For this reason, only use it when correctness is far more important than speed.


Summary. We saw that foreach is a powerful keyword for reducing bugs in loops, but it has no easy way to enumerate backwards. By using the Reverse extension method from System.Linq, we can do just that.

Caution: Reverse is creating a new IEnumerable collection, not simply doing a reverse iteration, making it less efficient.