C# Array Class
The array is one of those data structures which have been in use since the advent of the programming languages. Be it C, C++, Java, PHP or any other web-based, desktop or mobile application development, you will find an array data structure to hold records of data. Syntax may be different but the concept would be same. Keeping in view the importance of array in application, .NET framework provides you an explicit Array class that performs functionalities of a standard array.
The Array class in .NET serves as base class for all the single and multi-dimensional arrays. Of all the collection classes that .NET framework provides, the Array class is the one that implements all standard collection interfaces. Another exciting feature of the Array class is type unification which allows all the arrays to have a common set of methods that can be array irrespective of the type of the array.
As aforementioned, all the collection interfaces are implemented by the Array class, up to IList<T> interface. While implementing IList<T> interface, the Array class makes slight modification. The Add() and Remove() methods which are usually public in the classes that implement IList<T>interface, are not public in Array class because on fixed-length collections such as arrays, these methods throw exception. But Array class has a Resize method. You must be wondering that if array are fixed size collection then how it can be resized. The answer is that when you call static resize method on an array, what actually happens is that internally a new array of the specified size is created and all the elements in old array are copied into the new one. However, it is recommended that you should use IList collection if you want a resizable collection.
An interesting thing to note here is that, an Array class can store both reference as well as value types. Value types are stored directly in an array and occupy contagious memory locations, where as reference types are not stored directly in the memory; instead they are stored in non-contagious memory locations and their references are stored contagiously in an array. For instance, you have 4 long integers and you want to store them in an array. They would take 32 bytes of contagious memory locations. (One long integer contains 8 bytes). However, in case of reference variables, the reference of value types will be stored in memory which will be 4 bytes in case of a 32 bit system and 8 bytes in case of a 64 bit system.
.NET framework provides special types for these purposes, which are called StrucuturalComparison types. These types allow developer to compare if array contains similar elements or not. Before using StructuralComparison types, we have to first create an object if IStructuralEquatable interface. This interface has an Equals method to which we pass StructuralComparison type. We did this in the following line of code
In C#, there are two ways to construct arrays. You can use C# language construct to create arrays. This is more traditional way of construction arrays. Consider Example2 to see how arrays can be created in C# in traditional ways.
In the next line of code we have accessed the index of the array using the following line of code
Now come to some more interesting facts, you can see that we have used foreach loop to traverse the elements of the array. It is due to the fact that Array class implements IEnumerable interface and any class that implements IEnumerable interface can be traversed using foreach loop. Therefore, we used foreach loop to display the elements of the array. The output of the code in Example2 is as follows.
Now a question should come to your mind that in the output, first five elements are the elements that we stored in the array, but why the last five elements are zero although we didn’t store zero in the last five indexes of the numbers array. The answer to this question is simple. In integer type array, if you do not store any element at array indexes, by default zero is stored in that index when program is compiled. You can also dynamically store elements in array during declaration as we did in Example1 where we stored elements dynamically in arr1 and arr2 using following lines of code.
You can create an array in C# by calling Array.CreateInstance method where you can dynamically specify the type of the array along with the dimensions of the array. C# contains GetValue and SetValue static methods which can be used to get and set values at particular index of the array. In our next example, we are going to explain that how arrays can be created using Array.CreateInstance and how index can be accessed using GetValue and SetValue methods. Have a look at Example3.
In the next lines of code, we have called SetValue static method on numbers array and have stored values in it. SetValue method takes two parameters, first one is the object you want to store and the second parameter is the index at which you want to store your object. So the line ‘numbers.SetValue(30, 2)’ means that in array numbers store value 30 at index 2 which is actually the third index since array indexes start from 0. We have stored five values by calling this SetValue method and have then printed them using foreach loop.
Next, we have explained how you can use GetValue method to access particular element in this following line.
We can also cast arrays created using Array.CreateInstance method to traditional arrays. We have done this in Example3 in following lines.
Array class offers wide variety of methods for searching elements within an array. Following are some of the searching methods.
Next, we have explained the usage of FindAll method. This method also takes two parameters: first is the array in which searching has to be performed and the second parameter is the predicate which is lambda expression in our case. Difference between a simple Find method and FindAll method is that the former returns single element whereas the latter returns array of elements that satisfy the predicate. In our Example, we have written a lambda expression which finds all the string elements that ends with string ‘a’. As in our cars array we have three strings that end with ‘a’ therefore FindAll method would return a string array that would contain elements ‘Toyota’, ‘Honda’ and ‘Santra’. The output of the code in Example4 is as follows.
It can be seen that the first element is ‘Suzuki’ which would be returned by Find method where we have a predicate which finds elements that end with ‘i’. Similarly, the next three strings are the ones which end with ‘a’ as specified in FindAll method.
The next important task that we often need to perform is sorting the elements in an array. Fortunately enough, .NET framework provides built-in array sorting mechanism. In our next example we are going to explain with the help of example that how you can sort a C# array by calling sort method. Have a look at our 5th example of this article.
Next line of code is important, here we have called ‘Sort’ static method of array class and have passed it out unsorted array. This method would internally sort the elements of the array. We have again displayed the elements of the numbers array and this time you would see that elements have been displayed in the sorted order.
Now come towards an even interesting aspect of Sort method. We again declared an integer type array and named it numbers2 and again stored first 6 integers in it in random order. We then declared a string type array and have stored six elements in it. These elements are basically numbers from 1 to 6 in words. We then called Sort method of the Array class and then passed both numbers2 and words arrays as parameter. Now, what happens is that actually Sort method, before sorting would map the first element of the first array to the first element of the second array. Therefore, integer 4 of the numbers2 array would be mapped to “Four” string of the words array. Simply putting, first element of the first array maps to first element of the second array. Second element of the first array maps to second element of the second array and so on and so forth. It doesn’t matter that there has to be string “Four” at the first index of the words array. Anything at the first index of words array would be mapped to first index of the numbers2 arrays. Now, when sorting is done, it would be done on the basis of the first arrays, which means that when Sort method places integer ‘1’ on the first index of the numbers2 array, it would look that which element in the second array was mapped to the integer 1 in the first array. It would find that string “One” was mapped to integer 1. Therefore, in the words array, it would store “One” on first index. And this way, all the elements in both arrays would be sorted.
Array class is an extremely important type in C# programming and is probably the most widely used collection for storing elements. In this article, we have briefly explored some of the most fascinating and useful features of Array class. I would recommend you to further explore this class own your own and implement the remaining array methods that have not been explained in this article.
|All times are GMT +5.5. The time now is 09:06.|