Arrays in C#

Illustration: C# Arrays Tutorial - Understanding the fundamentals of arrays in C# programming with examples and best practices.

What is C# Array?

The array is a data structure in C# that can store multiple variables of the same type.

int[] intArr = new int[] { 15, 35, 50, 75, 100 };

For example, you want to store the product_id of the products or roll numbers of the students that are integer types.

One way can be declaring and storing the values in the primitive type variables. The other way can be creating an array that can store n number of int type variables for storing the product_id or roll_no etc.

The next sections describe how to create, initialize, and use arrays. I will also show you examples of various array types; single dimensional, multi-dimensional and Jagged arrays.

How to create and initialize an Array in C#?

The general syntax of creating/declaring an array is:

type[] NameOfArray;

For example:

int[] intArray;

string[] strArray;

The array can be initiated at the time of declaration. For example:

int[] intArray = new int[] { 5, 10, 14, 21 };

string[] strArray = new string[] {“abc”,”def”,”ghi”,”klm”};

An example of declaring, initiating, and accessing array elements

Let us start with a simple example of declaring and initializing an int-type array of five elements.

This is followed by using a C# for loop with the array length property to access and display the array elements:

using System;

class array_demo

{
    static void Main()
    {
        //Declaring and initializing an array
        int[] intArr = new int[] { 15, 35, 50, 75, 100 };

        for (int l = 0; l < intArr.Length; l++)
        {
            Console.WriteLine(intArr[l]);
        }
        Console.ReadLine();
    }
}

The result:

15

35

50

75

100

The example of C# string array

The example below creates an array of string type and then its items are accessed by using for loop and displayed on the screen:

The code:

using System;
class array_demo
{
    static void Main()
    {

        //Declaring and initializing a string array
        string[] strArrName = new string[] { "Hine", "Tina", "Mina", "Nazo", "Marie" };

        Console.WriteLine("****The Names in Array:****\n");
 
       for (int x = 0; x < strArrName.Length; x++)
        {
            Console.WriteLine("\t" + strArrName[x]);
        }
        Console.ReadLine();
    }
}

The output:

c sharp array-string

Using foreach loop to iterate through array elements example

You may also use foreach loop to iterate through the array elements.

using System;

class array_demo_foreach
{
    static void Main()
    {
        //Declaring a byte array
        byte[] bteArrNums = new byte[] { 1, 3, 5, 7 };

        foreach (byte num in bteArrNums)
        {
            Console.WriteLine("the Byte Array Item = " + num);
        }
        Console.ReadLine();
    }
}

c# array-foreach

The example of using Array sort method

Before showing you how to create multi-dimensional and jagged arrays in C#, let us have a look at a few useful methods and a property of the Array class.

The sort() method is used to sort the elements in a one-dimensional array. The example below shows how to use the sort method for primitive type array.

For that, we have an array of byte type with random numbers.

Then a foreach loop is used to display the array elements which is followed by using the sort() method.

To see the difference, the array elements are displayed again after sorting the array:

using System;

class array_demo_sort

{
    static void Main()
    {
        //Declaring a byte array
        byte[] bteArrSort = new byte[] { 99, 8, 5, 11, 21, 4 };

        Console.WriteLine("***Array Before Sorting***\n");

        foreach (byte num in bteArrSort)
        {
            Console.WriteLine("\t" + num);
        }

        Array.Sort(bteArrSort);

        Console.WriteLine("\n***Array After Sorting***\n");
        foreach (byte num in bteArrSort)
        {
            Console.WriteLine("\t" + num);
        }
        Console.ReadLine();
    }
}

c# array-sort

Sorting only a range of items

You may also specify the range of elements to be sorted by providing indices. For example, if we have the same array as above example:

byte[] bteArrSort = new byte[] { 99, 8, 5, 11, 21, 4 };

We are required to sort it from second to fourth elements only then the sort() method can be used as follows:

Array.Sort(bteArrSort, 1, 3);

The result of this should be (if you iterate through this array and display the items):

99

5

8

11

21

4

The example of Array IndexOf method

The IndexOf method of the Array is used to search objects in the one-dimensional array.  The IndexOf returns an integer value of the first matched element in the array.

So, if the specified array has duplicate occurrences, the method returns only the first found element’s position.

using System;

class array_demo_IndexOf
{
    static void Main()
    {
        int[] intArr_indexOf = new int[] { 15, 35, 50, 75, 100, 15, 75 };

        //Using the Array IndexOf method
        int x = Array.IndexOf(intArr_indexOf, 75);
        Console.WriteLine("The Position of the element = " + x);

        Console.ReadLine();
    }
}

The result:

The Position of the element = 3

You may notice, we searched 75 in the array. It occurred twice in the array while IndexOf returned the index position of the first 75 i.e. 3.

You may search a part of the array rather than a complete array by specifying the range of elements.

For example, if we used the IndexOf method like this in the above example:

int x = Array.IndexOf(intArr_indexOf, 75, 4);

The result should be:

The Position of the element = 6

As such, we specified to start searching the array from position 4.

An example of Array length property

The length property of the array gets the total number of elements in the specified array.

You might have noticed, we used it in our first example in the for loop.

It set the condition part in the for loop as shown below:

for (int l = 0; l < intArr.Length; l++)

{

Console.WriteLine(intArr[l]);

}

The example below shows the total number of elements in a string array by using the length property of the Array:

using System;

class array_demo_length
{
    static void Main()
    {
        string[] strArrAlphabets = new string[] { "abc", "def", "ghi", "jkl", "mno", "pqr", "stu", "vwx", "yz" };

        Console.WriteLine("Total Number of Elements in String Array = " + strArrAlphabets.Length);
        Console.ReadLine();
    }
}

The output of the above code:

Total Number of Elements in String Array = 9

An example of C# multi-dimensional array

C# supports multi-dimensional arrays. The general syntax of creating a 2D array of string type is:

string [,] Arr2D;

Where Arr2D is the array name.

Similarly, a three dimensional array can be declared as follows:

string [ , , ] Arr3D;

The example below shows how to create a two-dimensional array in C#.

using System;

class array_demo_2D
{
    static void Main()
    {
        string[,] Arr2D = new string[3, 2]
            { { "Mango", "Apple" },
            { "Banana", "Strawberry" },
            { "Pine Apple", "Peach" }
            };

        int x, y;

        for (x = 0; x < 3; x++)
        {
         for (y = 0; y < 2; y++)
         {
          Console.WriteLine("x[{0},{1}] = {2}", x, y, Arr2D[x, y]);
         }
       }
       Console.ReadLine();
    }
}

The result:

c# array-2D

C# Jagged array example

The array of arrays is called a jagged array. C# supports a Jagged array that can be declared as follows:
int [][] ArrJagged;

See an example below for declaring, initializing, and accessing a jagged array of string type:

using System;

class array_demo_Jagged
{
    static void Main()
    {
        string[][] ArrJagged = new string[][]
            {new string[]{"abc","def"},
            new string[]{"ghi","kjl"},
            new string[]{"mno","pqr"},
         };

        int i, j;

        Console.WriteLine(ArrJagged[0][0]);
        Console.WriteLine(ArrJagged[0][1]);
        Console.WriteLine(ArrJagged[1][0]);
        Console.WriteLine(ArrJagged[1][1]);

        Console.ReadLine();
    }
}

The result:

abc

def

ghi

kjl

Summary of C# Arrays Tutorial

This C# arrays tutorial covers fundamental aspects of array manipulation and usage. Here are the key points:
  • Array declaration and initialization: Learn the syntax for declaring and initializing arrays of different data types, including both fixed-size and dynamic initialization.
  • Accessing array elements: Explore various methods to access and iterate through array elements, including using for loops and foreach loops.
  • Useful methods and properties: Discover essential methods like sort() for sorting elements, IndexOf for searching elements, and length property for retrieving the total number of elements.
  • Multi-dimensional arrays: Go beyond one-dimensional arrays and learn how to create and use two-dimensional and three-dimensional arrays.
  • Jagged arrays: Understand the concept of jagged arrays and how to declare, initialize, and access their elements.
Author - Atiq Zia

Atiq is the writer at jquery-az.com, an online tutorial website started in 2014. With a passion for coding and solutions, I navigate through various languages and frameworks. Follow along as we solve the mysteries of coding together!