Working with Arrays in C#

Arrays are frequently used to store data of the same type. You can use arrays in C# in many different ways. Although single dimensional arrays are most commonly used, other varieties such as multidimensional arrays and jagged arrays are also available to C# developers. Additionally, the Array class comes in handy when it comes to sorting or searching an array. This article discusses all these types of arrays with examples of each.

Overview of Arrays

Arrays allow you to store a series of values belonging to the same data type. Each piece of data that you store in an array is called as an element. You can create arrays for storing primitive data types as well as object data types. While creating an array you need to specify the data type that each of its elements will hold as well as the total number of elements in the array. Arrays can be single dimensional, multidimensional or jagged. You will learn about these three types in the following sections. For now have a look at the following figure that shows a single dimensional array of integers (primitive type) and a single dimensional array of Customer objects (object data type).

A single dimensional array of Integers and Customer objects

As you can see from the figure, the memory address of the array variable is stored in stack memory whereas the elements are stored on managed heap. In the case of integer array, integer being a value type, the elements will contain the respective values. On the other hand the Customer being a reference type, the elements will hold a reference to the actual Customer objects.

Single Dimensional Arrays

Now let's see how to create and use a single dimensional array. A single dimensional array consists of a contiguous series of elements. While declaring such an array you need to tell the compiler about the data type of the array and the total number of elements that it is going to hold. Consider the following piece of code:

The above code declares an array of integers named intArray. Notice how [] are placed after int type to indicate that we intend to create an array. Then the new keyword is used to create the integer array with 10 elements. The number you specify in the [ and ] indicates the total number of elements in the array (10 in this case). There are a couple of other ways to create an array if you wish to assign values to individual elements while creating the array itself. They are shown below:

The first line of the above fragment creates an integer array with three elements and also assigns values to those three elements (10, 20 and 30 respectively). The second line is another way to achieve the same task. It omits the new keyword altogether. In both of the cases the C# compiler determines the total number of array elements based on the values you supply. In the above case, since you supplied three values, intArray will have three elements.

Now let's go back to the first code listing of this section. After declaring an integer array the code runs a for loop. Notice how the Length property of the array variable is used to determine the total number of elements in the array. Inside this for loop the code assigns values to individual array elements. To assign a value to an array element you need to use the element index in [ ]. Array element index starts from 0. That means first array element has an index of 0, the second element has an index of 1 and so on. Obviously the maximum index number that an array can have is (total no. of elements - 1). That's the reason the for loop terminating condition is i < intArray.Length.

Next, a foreach loop iterates through the array and outputs the value of each element on the console. Notice that variable j is defined with int data type since the array is an integer array. You can also use the var keyword instead of declaring j of type int:

foreach (var j in intArray)
{
Console.WriteLine(j);
}

Now that you know how to create single dimensional arrays of primitive data types, let's see how to create arrays of reference types. Consider the following piece of code:

The first line of the above code fragment declares an array of Customer objects. The size of the array is three. Note that at this point in time only the length of the array is known. The individual array elements are still null.

Then the code illustrates various ways of assigning elements of an object array. In the first way a Customer object is instantiated using the new keyword and is immediately assigned to the 0th element of the array. The second way creates a new Customer object and assigns to the second array element. Then the properties of Customer object are assigned. In the third way a stand-alone Customer object is created and then its reference is assigned to the third element of the array.

You can use the same techniques to iterate an array of reference type as that of the array of primitive types (for and foreach). The following code shows how to use foreach with the Customer array.

Multidimensional Arrays

In a single dimensional array elements are accessed by a single index number that represents the position of that element. It is also possible to store data in multidimensional arrays. In the latter case an array element is accessed by two or more integers that represent the position of an element. Consider the following code that creates a two dimensional array.

The above code creates a two dimensional array that has two rows and two columns. Notice how the dimensions are indicated by [ , ] syntax. Thus the Length property of intArray will be 4. Each element can be accessed using the row and column number as shown. You can also initialize two dimensional arrays at the time of creation:

int[,] intArray = { { 10, 20 }, { 30, 40 } };

On the same lines you can also create three or more dimensional arrays. For example, here is how a three dimensional array can be created:

int[, ,] intArray = { { { 10, 20 }, { 30, 40 } } };

Jagged Arrays

In the previous example you created a two dimensional array. A two dimensional array has the same number of columns in all the rows. It is also possible to have a different number of columns in each row using what is called as Jagged array. A jagged array is an array or arrays. Using jagged array you can create an array of say 2 rows, with the first row containing say 3 elements and second row containing 6 elements. The following code shows how this works:

In this piece of code you use a bit different syntax while creating the array. Notice the use of [ ] [ ] in this case. The declaration indicates that the jagged array will have 2 rows but an unknown number of elements. While initializing each row you specify the exact number of elements. In other words, each element of the jagged array is an array. Iterating through a jagged array is easy, as shown by the nested for loops that follow the array initialization.

Array Class

Although C# provides inbuilt keywords to create and initialize arrays, behind the scenes it actually relies on System.Array class for its functionality. For example, the Length property that you used in the earlier examples actually comes from the Array class. Some of the other situations where Array class comes in handy include array sorting and searching. Consider a case where you have an array that stores some string values and before displaying them to the user you wish to sort them. Array class can do that job for you with its Sort() method. The following example shows how:

In this overload you specify the Comparison parameter that compares the two strings using the CompareTo() method.

Summary

Arrays are commonly used in C# applications. C# allows you to create single dimensional, multidimensional and jagged arrays. Behind the scenes, C# arrays make use of the System.Array class. This article illustrated several ways of creating and initializing arrays in C#. It also illustrated how the Array class can be used for sorting a string array.

About the Author:

Bipin Joshi is a blogger, author and an IT trainer who writes about apparently unrelated topics - Yoga & technology! Bipin has been programming since 1995 and is working with .NET framework ever since its inception. He has authored or co-authored half a dozen books and numerous articles on .NET technologies. He has also penned a few books on Yoga. You can read more about him here.

Top White Papers and Webcasts

Live Event Date: March 19, 2015 @ 1:00 p.m. ET / 10:00 a.m. PT
The 2015 Enterprise Mobile Application Survey asked 250 mobility professionals what their biggest mobile challenges are, how many employees they are equipping with mobile apps, and their methods for driving value with mobility.
Join Dan Woods, Editor and CTO of CITO Research, and Alan Murray, SVP of Products at Apperian, as they break down the results of this survey and discuss how enterprises are using mobile application management and private …

Today's agile organizations pose operations teams with a tremendous challenge: to deploy new releases to production immediately after development and testing is completed. To ensure that applications are deployed successfully, an automatic and transparent process is required. We refer to this process as Zero Touch Deployment™. This white paper reviews two approaches to Zero Touch Deployment--a script-based solution and a release automation platform. The article discusses how each can solve the key …