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
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:

int[] intArray = new int[10];
 
for (int i = 0; i < intArray.Length; i++)
{
    intArray[i] = i;
}
 
foreach (int j in intArray)
{
    Console.WriteLine(j);
}

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:

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

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:

Customer[] custArray = new Customer[3];
 
//one way of assigning elements
custArray[0] = new Customer {CustomerID=10,CompanyName="Company 1",ContactName="Contact 1",Country="Country 1" };
 
//another way of assigning elements
custArray[1] = new Customer();
custArray[1].CustomerID = 20;
custArray[1].CompanyName = "Company 2";
custArray[1].ContactName = "Contact 2";
custArray[1].Country = "Country 2";
 
//yet another way of assigning elements
Customer obj = new Customer { CustomerID = 30, CompanyName = "Company 3", ContactName = "Contact 3", Country = "Country 3" };
custArray[2] = obj;

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.

foreach (var obj in custArray)
{
    Console.WriteLine(obj.CompanyName);
}

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.

int[,] intArray = new int[2, 2];
 
intArray[0, 0] = 10;
intArray[0, 1] = 20;
intArray[1, 0] = 30;
intArray[1, 1] = 40;
 
Console.WriteLine(intArray.Length);
Console.ReadLine();

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:

int[][] intArray = new int[2][];
intArray[0] = new int[3] { 10, 20, 30 };
intArray[1] = new int[6] { 40, 50, 60, 70, 80, 90 };
 
for (int i = 0; i < intArray.Length; i++)
{
    for (int j = 0; j < intArray[i].Length; j++)
    {
        Console.WriteLine(intArray[i][j]);
    }
}

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:

string[] colors = { "red", "green", "blue", "yellow", "orange" };
Array.Sort(colors);
 
foreach(string s in colors)
{
    Console.WriteLine(s);
}
Console.ReadLine();

The above code sorts a string array – colors – in ascending order. If you see the output of this program you will find that the colors are listed as:

blue
green
orange
red
yellow

In case you wish to sort the colors in descending order you can use another overload of the Sort() method:

 Array.Sort<string>(colors, new Comparison<string>((s1, s2) => s2.CompareTo(s1)));

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.

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read