Array Class C# Help

Declaring an array with brackets is a C# notation of using the Array class. Using the C# syntax behind the scenes creates a new class that derives from the abstract base class Array. It is possible, in this way, to use methods and properties that are defined with the Array class with every C# array. For example, you’ve already used the Length property or iterated through the array by using the foreach statement. By doing this, you are using the GetEnumerator () method of the Array class.


The Array class contains the properties listed in the following table that you can use with every array instance. More properties are available, which are discussed later in this chapter.


The Length property returns the number of elements inside the array. If the array is a multidimensional array, you get the number of elements of all ranks. If you need to know the number of elements within a dimension, you can use the GetLength () method instead.


The Length property returns an int value; the LongLength property returns the length in a long value. If the array contains more elements than fit into a 32-bit int value, you need to use the LongLength property to get the number of elements.


With the Rank property you get the number of dimensions of the array.

Creating Arrays

The Array class is abstract, so you cannot create an array by using a constructor. However, instead of using the C# syntax to create array instances, it is also possibleto create arrays by using the static. Createlnstance () method. This is extremely useful if you don’t know the type 01 the elements in advance, because the type can be passed to the Createlnstance () method as a Type object.

The following example shows how to create an array of type int with a size of 5. The first argument of the CreatelnstanGe () method requires the type of the elements, and the second argument defines
the size. You can set values with the SetValue () method, and read values with the GetValue ( ) method.

Array intArrayl = Array.Createlnstance(typeof(int), 5);

for (int i = 0; i < 5; i++)
intArrayl.SetValue(33, i);
for (int i = 0; i < 5; i++)
. Console.WriteLine(intArrayl.GetValue(i»;

You can also cast the created array to an array declared as int []:

The Create Instance () method has many overloads to create multidimensional array & and also to create arrays that are not O-based.The following example creates a 2-dimensional arraywith 2 x 3 elements. The first dimension is I-based: the second dimension is 100 based.

int[1] lengths: { 2, 3 };
int [] lowerBounds = { 1·, 10 };
Array racers = Array.CreateInstance (typeof (Person) , lengths, lowerBounds);

Setting the elements of the array, the SetValue () method accepts indices for every dimension:

racers.SetValue(new Person(“Alain”, “Prost”), 1, 10);
racers.SetValue(new Person(“Emerson”, “Fittipaldi”), 1, 11);
racers.SetValue(new Person(“Ayrton”, “Senna”), 1, 12);
racers.SetValue(new Person(“Ralf”, “Schumacher”), 2,.10);
racers.SetValue(new Person(“Fernando”, “Alonso”), 2, 11);
racers.SetValue(new Person(“Jenson”, “Button”), 2, 12);

Although the array is not O-based you can assign it to a variable with the normal Of notation. You just have to pay attention to not crossing the boundaries.

Person[] racers2 = (Person[,])racers;
Person first = racers2[1, 10];
Person last = racers2[2, i2];

Copying Arrays

Because arrays are reference types, assigning an array variable to another one just gives you two variables referencing the same array. For copying arrays, the array implements the interface ICloneable. The Clone () method that is defined with this interface creates a shallow copy of the array.

If the elements of the array are value types, as in the following code segment, all values are copied, as you can see,

int() intArray1 {1, 2};
int() intArray2 (int[])intArray1.Clone();

If the array contains reference types, only the references are copied; not the elements. It shows the variables beatles and beatlesClone, where beatlesClone is created by calling the Clone!) method from beatles. The Person objects that are referenced are the same with beatles and beatlesClone. If you change a property of an element of beatlesClone, you change the same object of beatles.

Person[] beatles = {
new Person (“John”, “Lennon”), .
new Person(“Paul”, “McCartney”)
Person[] beatlesC10ne = (Person[])beatles.Clone();

Instead of using the Clone () method, you can use the Array _Copy() method, which creates a shallow copy as well. But there’s one important difference with Clone () and Copy() : Clone () creates a new array; with Copy() you have to pass an existing array with the same rank and enough elements.

If you need a deep copy of an array containing reference types, you have to iterate the array and create new objects.


The Array class implements a bubble-sort for sorting the elements in the array.The Sort () method requires the interface IComparable to be implemented by the elements in the array. Simple types such as System. String and System. Int32 implement IComparable, so you can sort elements containing these types.

With the sample program, the array name contains elements of type string, and this array can be sorted:

The output ~the application shows the sorted result of the array:

Christina Aguilela
Gwen Stefani

If you are using custom classes with the array, you must implement the interface IComparable. This interface defines just one method, compareTo ( ), that must return 0 if the objects to compare are equal, a value smaller than 0 if the instance should go before the object from the parameter, and a value larger than 0 if the instance should go after the object from the parameter.

Change the Person class to implement the interface IComparable. The comparison is done on the value of the La·stName.Because the LastName is of type string, and the String class already implements theIComparable interface, with the implementation you can rely on the CompareTo () method of the String class. If the LastName has the same value, the FirstName is compared:

Now it is possible to sort an array of Person objects by the last name:

Person[] persons = (
new Person(‘Emerson’, ‘Fittipaldi’),
new Person(‘Niki’, ‘Lauda’),
new Person(‘Ayrton’, ‘Senna’),
new Person (‘Michael’, ‘Schumacher’)
} ;
foreach (Person p in persons)


Using the sort of the Person class, the output returns the names sorted by the last name:

Emerson Fittipaldi
Niki Lauda
Michael Schumacher
Ayrton Senna

If the Person objecfshould be sorted differently, or if you don’t have the option to change the class that is used as an element in the array, you can implement the interface IComparer. This interface defines the method-compe re ( ) . The interface IComparable must be implemented by the class that should be compared. The IComparer interface is independent of the class to compare. That’s why the Compare ( ) method defines two arguments that should be compared. The return value is similar to the CompareTo () method of the IComparable interface.

The class PersonComparer implements the IComparer interface to sort Person objects either by firstName or by lastName. The enumeration PersonCompareType defines the different ‘ sorting options that are available with the PersonComparer: FirstName and LastName. How the compare should happen is defined with the constructor of the class PersonComparer where a PersonCompareType value is set. The Compare () method is implemented with a swi tch statement to compare either by LastName or by FirstName.

Now you can pass a PersonComparer object to the second argument of the Array. Sort () method. Here the persons are sorted by first name:

Array. Sort (persons,
new PersonComparer(
FirstName) );
foreach (Person p in persons)


The persons array is now sorted by the first name:

Ayrton Senna
Emerson Fittipaldi
Michael Schumacher
Niki Lauda

The Array class also offersSort methods thllt require delegate as an argument.

Posted on October 28, 2015 in Arrays

Share the Story

Back to Top
Share This