Array in C# - single, multiple and jagged array

An array can be initialized in several ways, it can store a single value or series of values, every element must be set of same type, C# supports single-dimensional arrays, multidimensional arrays (also call rectangular array) and array-of-arrays (referred jagged arrays), let’s discuss features of array in C# like how to declare array in C#, How to initialize values to an array, how to define the size of the array etc.

In C# arrays are object and must be initialized, start with index zero (0), and works in same ways as other popular languages but there are some differences, when we declare an array we use [] after type and not after the variable (not the identifier) e.g.

int[] myarr;  //not int myarr[]

How to declare and initialize a single dimensional array:

// Declare a single-dimensional array of type string  
string[] array = new string[3];

// Initialize it
array[0] = "Content 1";
array[1] = "Content 2";
array[2] = "Content 3";

// Read and write them on console
 for (int i = 0; i < array.Length; i++)
    Console.WriteLine(String.Format("{0}. {1}", i + 1, array[i]));

If you want to declare an array of type integer then just change it’s data type to int

 // Declare a single-dimensional array of type int  
 int[] array = new int[3];

and you can initialize it similar to string, is this only way to assign the array, no, you can also declare and initialize the array at same time, see this:

 int[] array = new int[] { 10, 20, 30, 40, 50 };
 //OR directly
 int[] array = { 10, 20, 30, 40, 50 };

Suppose I declare an array of type integer, and without initializing, I try to write it, can you guess what would be the output of following lines of code:

 int[] array = new int[2];
 for (int i = 0; i < array.Length; i++)
    Console.WriteLine(String.Format("{0}. {1}", i + 1, array[i]));

Here is the output:

  1. 0
  2. 0
  3. 0

So we knew that, the default values of numeric array elements are set to zero, and reference types array elements are set to null.

Single dimensional array used for linier operations like First come first out, or first come last out, here are some points we need to remember while working with single dimensional array

  1. Arrays in C# are zero indexed.
  2. An array with n elements is indexed from 0 to n-1.
  3. Array elements can be of any type, including an array type as well.
  4. Array types are reference types derived from the abstract base type Array.
  5. You can use for loop to access the elements one by one, in any direction, start to end or vise versa.
  6. Since this type implements IEnumerable and IEnumerable <T>, you can use foreach iteration on all arrays in C#.

Sort a single dimensional array:

Most of the time we gets array of string or numbers but they are not sorted or sorted in ascending order but we want the item in descending order, or array is sorted in descending order but we want it in ascending order then we have two methods OrderBy and OrderByDescending

int[] array = { 1, 30, 40, 23, 32, 12, 22, 98, 76, 57, 2, 34 };
array = array.OrderBy(x => x).ToArray();

foreach (var item in array)
    Console.Write(String.Format("{0} ", item));    

// OUTPUT:
 1 2 12 22 23 30 32 34 40 57 76 98

// To sort in descending order 
array = array. OrderByDescending (x => x).ToArray();
// OUTPUT:
98 76 57 40 34 32 30 23 22 12 1

Delete duplicate items from an array

Suppose I have single dimensional array, which contains many duplicate item, and I want to delete duplicate items then simply we will use Distinct method to get array of unique items, see this:

int[] array = { 10, 20, 30, 40, 50, 60, 70 ,80, 90, 100, 20,  40, 60, 80 };
array = array.Distinct().ToArray();

foreach (var item in array)
    Console.Write(String.Format("{0} ", item));

// OUTPUT :
10 20 30 40 50 60 70 80 90 100

Update an item in an array To update an item at any position in an array, you just need to know which element you want to update and simply re-assign a new value to that element, say I want to update 3rd and 5th element of an array then

array[2] = “new value for 3rd element”;
array[4] = “New value for 5th element”;

Note: I used 2 and 4 the index and not the 3 and 5, as we already discussed array in C# are indexed 0.

Multi-dimensional array:

Two dimensional array is the simplest form of multi-dimensional array, it can be thought as a table, which can contain N number of rows and M number of columns.

alt text

Take the example of a hotel, a guest comes to the counter and ask the detail of a person and operator says, 5th floor room number 15, so floor is the row and room number is the column. Suppose we have to store the same data into an array then how can we create our array, let's say, the hotel have 20 floors and maximum 50 rooms on a floors, then we can declare an array like this:

String[,] hotel = new string[20, 50];

// Assign 5th floor room number 10 to Mr. John
hotel[4, 9] = "Mr. John";

// Assign 20th floor room number 45 to Mr. Smith
hotel[19, 44] = "Mr. Smith";

// Assign 17th floor room number 1 to Mr. George
hotel[16, 0] = "Mr. George";

// Assign 20th floor room number 50 to Mr. Jeffry 
hotel[19, 49] = "Mr. Jeffry";

There is nothing special except we reduce 1 every time from the floor and room because we know C# array are indexed 0 (zero. If I ask to tell me, who is booked which room by telling you the floor and room number, would it be a difficult, I don't think so, let's try to get some name from our above hotel variable by providing room number and floor

// who booked floor: 11   room: 31
var bookedBy1 = hotel[10, 30];

// who booked floor: 9   room: 19
var bookedBy2 = hotel[8, 18];

// who booked floor: 8   room: 35
var bookedBy3 = hotel[7, 34];

// who booked floor: 17   room: 19
var bookedBy4 = hotel[16, 18];

Now we know how to assign any value in a two dimensional array and how to retrieve data by using the index (floor, room number), I don't think we need to show the result of above assignment.

Let’s take an example to create the table of numbers from 1 to 10. To create it we need an array of two dimensions with 10 rows and 10 columns, so let’s try it:

int[,] array = new int[10, 10];
// Create our desired table
for (int i = 0; i < 10; i++)
    for (int j = 0; j < 10; j++)
        array[i, j] = (i + 1) * (j + 1);

 // Print our table
for (int i = 0; i < 10; i++)
{
    for (int j = 0; j < 10; j++)
    {
        Console.Write(String.Format("{0} ", array[i, j]));

    }
    Console.WriteLine();
}

// OUTPUT
  1   2   3   4   5   6   7   8   9  10
  2   4   6   8  10  12  14  16  18  20
  3   6   9  12  15  18  21  24  27  30
  4   8  12  16  20  24  28  32  36  40
  5  10  15  20  25  30  35  40  45  50
  6  12  18  24  30  36  42  48  54  60
  7  14  21  28  35  42  49  56  63  70
  8  16  24  32  40  48  56  64  72  80
  9  18  27  36  45  54  63  72  81  90
 10  20  30  40  50  60  70  80  90 100  

Jagged Arrays

  1. It is also called array of array.
  2. A jagged array is an array whose elements are also arrays.
  3. The elements of a jagged array can be of different dimensions and sizes.
  4. Before you can use jagged array, its elements must be initialized.
  5. The element array can be of any length.

Let’s see some examples, declare a single-dimensional array that has three elements, each of which is a single-dimensional array of integers

int[][] array = new int[3][];
// Initialize it
array[0] = new int[5];
array[1] = new int[3];
array[2] = new int[1];

// Or we can directly initialize it without specifying the length
array[0] = new int[] { 1, 3, 5, 7, 9 };
array[1] = new int[] { 4, 6, 8, 10 };
array[2] = new int[] { 20, 30 };

foreach (int[] arr in array)
{
    foreach (int item in arr)
    {
        Console.Write(String.Format("{0} ", item));
    }
    Console.WriteLine();
}
// OUTPUT
1 3 5 7 9
4 6 8 10
20 30

The article will not complete if we will not discuss about the “Implicit-Typed Array”. So let’s take an example, suppose we want to store student name and their marks then none of the above type of array is sufficient to serve the purpose so we need an implicit typed array, see it in action:

var array = new[]
{
    new{
        Student = "Ajay Singh",
        Marks = new int[] {50, 91, 60, 35, 77}
    },
    new{
        Student = "Vijay Rawat",
        Marks = new int[] {60, 57, 80, 49, 87}
    },
    new{
        Student = "Sunil Kumar",
        Marks = new int[] {63, 69, 75, 77, 80}
    },
    new{
        Student = "Jeffery",
        Marks = new int[] {80, 57, 61, 35, 63}
    }
};

foreach (var row in array)
{
    Console.Write(String.Format("\n{0}: ", row.Student));
    foreach(var mark in row.Marks)
        Console.Write(String.Format("\t{0}  ", mark));

}
Console.Read();

Ajay Singh:     50      91      60      35      77
Vijay Rawat:    60      57      80      49      87
Sunil Kumar:    63      69      75      77      80
Jeffery:        80      57      61      35      63
Ali Adravi Having 13+ years of experience in Microsoft Technologies (C#, ASP.Net, MVC and SQL Server). Worked with Metaoption LLC, for more than 9 years and still with the same company. Always ready to learn new technologies and tricks.
  • c#
  • array
  • asp.net
By Ali Adravi On 24 Mar, 13  Viewed: 4,336

Other blogs you may like

Polymorphism in C# with example

Polymorphism is derived from two Latin words, 1. Poly means many 2. Marphose means forms. By using inheritance, a class can be used as many types, say we have a Person which may be a Professor, may be a Student, may be Clerk. So in this article we will see some example of Polymorphism. When we... By Hamden   On 01 Jun 2013  Viewed: 4,548

How to create windows service in C# visual studio 2010

Creating windows service in C# is really easy but when we need to create first time we face many problems so in this post we will try to learn everything about window service. In this article we will create a windows service which will run after a particular interval, and time should be... By Ali Adravi   On 30 Apr 2013  Viewed: 8,610

Covariance and Contravariance in C# 4.0 with example

C# the language, right from the very beginning is always supported covariance and contravariance but in most simple scenario, now in C# 4.0 we have full support of covariance and contravariance in all circumstances, generic interface and generic delegates, other C# types already support from first... By Ali Adravi   On 29 Mar 2013  Viewed: 4,977

default value for different data type in C#

In C# there are different data type and they use some default value when we declare a variable. When we define a variable of type int or Int32 say int score; so what is the value of score, will it be null or zero, in the same way if we create a variable of type string/String what value it holds... By Ali Adravi   On 27 Mar 2013  Viewed: 2,599

enum in C# and conversion

An enumeration type (also known an enumeration or an enum) provides an efficient way to define a set of named integral constants that may be assigned to a variable to make programming clear, understandable and manageable. There are ways of using, like how to use enum in switch and case statement,... By Hamden   On 27 Mar 2013  Viewed: 4,525