Site Search
Homepage of Otaku No Zoku
Complete Archives of Otaku No Zoku
About Otaku No Zoku
Subscribe to Otaku No Zoku
Bookmark Otaku No Zoku

C# Array.Sort Array Reference Example :

All arrays in .NET are derived from the Array base type, making an array a system object. The System.Array type is an abstract base type so cannot itself be instantiated. But the System.Array base type can be used to obtain a reference to a previously declared array.

Obtaining a reference to an array is trivial and once you have it, you can use the array reference as though it were the original array.

Sorting Of An Array Reference

This program sorts a reference to an array of unsorted integers, placing them in to their natural numerical order.

Steps

  1. Allocate a small array of integers that are not yet sorted.
  2. Obtain a reference to the array of integers.
  3. Use the Array.Sort method to sort the array of integers in to numerical order using the array reference.
  4. Print the sorted array of integers to the console.
  5. Print the sorted array reference to the console to compare.

The Source Code

using System; 

class ArrayReferenceSort
{
    static void Main()
    {
        // allocate a small array of ten integers
        int[] numericalValues = { 43, 7, 19, 99, 57, 25, 45, 12, 37, 28 };

        // grab a reference to the array of integers
        Array arrayOfValues = numericalValues;


        // sort the array reference in to natural numerical order
        Array.Sort(arrayOfValues);

        // output each number in the original array
        Console.WriteLine(String.Join(", ", numericalValues));

        // output each number in the array reference
        Console.WriteLine(String.Join(", ", (int[])arrayOfValues));
    }

}

Program Output

7, 12, 19, 25, 28, 37, 43, 45, 57, 99
7, 12, 19, 25, 28, 37, 43, 45, 57, 99

Results

Taking a look at the output you can clearly see that first line of text shows that the the array, numericValues, containing ten distinct integers in no particular order, has been sorted successfully. And that the second line of text, outputting the values referred to by arrayOfValues, which is the output from the array reference, has also been sorted. The array reference refers to the original data, so when you alter one, you alter the other along with it.

Summary

The method Array.Sort has 17 overloads as of .NET 4.0 offering the ability to sort many different types of arrays, including references to arrays.

Further Reading

  1. Sorting overview
  2. Sorting a range of elements with Array.Sort
  3. Sorting an array with Array.Sort
  4. Sorting two arrays of Keys & Values simultaneously with Array.Sort

Liked This Post?

Subscribe to the RSS feed or follow me on Twitter to stay up to date!