TheDeveloperBlog.com

Home | Contact Us

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

C# Array.Reverse Inverts Array Ordering

This C# program demonstrates Array.Reverse, which reverses the order of elements.

Array.Reverse inverts the ordering of an array's elements.

This task could be accomplished with a for-loop. But the Array.Reverse method is more convenient—and also easier to read. It is simple to use—we need the System namespace.

Example. First, please notice that the Array.Reverse method is a static method on the Array type. You should pass one argument to the method: the reference to the array you want to reverse. In this example, an integer array is used.

Static MethodInt Array

Then: Array.Reverse method is called twice. This reverses the original array, and then reverses the reversed array.

C# program that uses Array.Reverse method

using System;

class Program
{
    static void Main()
    {
	// Input array.
	int[] array = { 1, 2, 3 };

	// Print.
	foreach (int value in array)
	{
	    Console.WriteLine(value);
	}
	Console.WriteLine();

	// Reverse.
	Array.Reverse(array);

	// Print.
	foreach (int value in array)
	{
	    Console.WriteLine(value);
	}
	Console.WriteLine();

	// Reverse again.
	Array.Reverse(array);

	// Print.
	foreach (int value in array)
	{
	    Console.WriteLine(value);
	}
    }
}

Output

1
2
3

3
2
1

1
2
3

Internals. How does the Array.Reverse method work? In its .NET Framework 4.0 implementation, the method checks the parameter and then invokes TrySZReverse: this particular method is implemented in native code, not managed code.

Tip: Because this internal call is native, it is likely heavily optimized for performance.

Most important, though, is that Array.Reverse is easier to use than a custom reversal algorithm. Not only does Array.Reverse use native code, but it also makes your program simpler. It is an improvement.

Summary. Here we examined the Array.Reverse static method. This method receives an Array type parameter, such as an int array, and reverses the order of the elements in that same array. You do not need to allocate another array.


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