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.
This program sorts a reference to an array of unsorted integers, placing them in to their natural numerical order.
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));
}
}
7, 12, 19, 25, 28, 37, 43, 45, 57, 99
7, 12, 19, 25, 28, 37, 43, 45, 57, 99
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.
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.