TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

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. It returns the elements in the opposite order.

Example. First, we show how to invoke the Reverse extension method from the System.Linq namespace. Please notice that the program includes the System.Linq namespace at the top. This is important.

The Reverse extension method is not defined on the array type. Instead, it is defined in the LINQ library and can effectively act upon arrays. This program writes the opposite element order in the array to the screen.

Console.WriteLine

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

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. This requires more allocations and in the end results in worse performance.

Array.Reverse

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

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

Summary. The Reverse extension method is effective. But it may not be ideal for all programs in this context. Please carefully weigh the performance and conciseness demands of your program before choosing Reverse.

Review: The declarative, function-based syntax of Reverse is short but not optimally fast.


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf