C# Arrays with Examples

In c#, Arrays are useful to store a multiple elements of same data type at contiguous memory locations and an arrays will allow us to store fixed number of elements sequentially based on the predefined number of items.

 

In previous chapter, we learned about variables in c#, which will help us to hold a single value like int x = 10;. In case if we want to hold more than one value of same data type, then an arrays came into the picture in c# to solve this problem.

 

An array can start storing the values from index 0. Suppose if we have an array with n elements, then it will start storing the elements from index 0 to n-1.

 

Following is the pictorial representation of storing the multiple values of same type in c# array data structure.

 

C# Arrays Structure Representation

 

If you observe above diagram, we are storing the values in an array starting from the index 0 and it will continue to store the values based on the defined number of elements.

C# Arrays Declaration

In c#, Arrays can be declared by specifying the type of an elements followed by the square brackets [] like as shown below.

 

type[] array_name; 

Here the type is nothing but a data type of an elements to store in an array and array_name represents the name of an array.

 

For example, following are the different ways of declaring an array with different data types in c# programming language.

 

// Store only int values

int[] numbers;

//Store only string values

string[] names;

//Store only double values

double[] ranges;

If you observe above examples, we declared an arrays with required data type based on our requirements.

 

In c#, the array elements can be of any type and by default the values of numeric array elements are set to zero and the reference elements are set to null.

C# Arrays Initialization

In c#, Arrays can be initialized by creating an instance of array with new keyword. By using new keyword we can declare and initialize an array at the same time based on our requirements.

 

Following are the different ways of declaring and initializing an array elements by using new keyword in c# programming language.

 

// Declaring and Initializing an array with size of 5

int[] array = new int[5];

//Defining and assigning an elements at the same time

int[] array2 = new int[5]{1,2,3,4,5};

//Initialize with 5 elements will indicates the size of an array

int[] array3 = new int[] { 1, 2, 3, 4, 5 };

// Another way to initialize an array without size

int[] array4 = { 1, 2, 3, 4, 5 };

// Declare an array without initialization

int[] array5;

array5 = new int[]{ 1, 2, 3, 4, 5 };

If you observe above examples, in first statement we declared and initialized an integer array with the size of 5 to allow an array to store 5 integer values and the array can contain an elements from array[0] to array[4].

 

In second statement, we declared and initialized an array same like first statement but also assigned a values to each index followed by curly brackets { }.

 

In third or fourth statement, while declaration we initialized an array with values, but without specifying any size. Here, the size of an array can be determined by the number of elements so the size initializer is not required if we are assigning an elements during the initialization.

 

In c#, we can declare an array variable without initialization, but we must use new keyword to assign an array to the variable.

 

In fifth statement, we declared an array without initialization and we used a new keyword to assign an array values to the variable.

 

In c#, after an array declaration we can initialize an array elements using index values. Following is example of declaring and initializing an array elements using individual index values in c#.

 

int[] array = new int[5];

array[0] = 1;

array[1] = 2;

array[2] = 3;

array[3] = 4;

array[4] = 5;

If you observe above example, we are initializing an array elements individual using individual index values.

 

Generally, in c# initializing an array without size or assigning a values to an array without new operator will throw a compile time errors. For example:

 

// Error. Initialize an array without size

int[] array = new int[];

// Error. Initialize an array without new keyword

int[] array1;

array1 = { 1, 2, 3, 4, 5 };

If you observe above examples, in first statement we initialized an array without any size and in second statement we declared and initializing an array elements without using new keyword. These two statements will throw a compile time errors in our c# applications.

C# Accessing an Array Elements

In c#, we can access an array elements by using for loop or foreach loop or with particular index numbers.

 

Following is the code snippet of accessing an array elements by using particular index numbers.

 

int[] array = new int[5] { 1, 2, 3, 4, 5 };

int a = array[1]; // It will return 2

int b = array[4]; // It will return 5

If you observe above code, we are trying to access an array elements using index values in c#.

 

Following is the example of declaring, initializing and accessing an array elements with particular index numbers in c# programming language.

 

using System;

 

namespace Tutlane

{

    class Program

    {

        static void Main(string[] args)

        {

            int[] array = new int[5] { 1, 2, 3, 4, 5 };

            Console.WriteLine(array[0]);

            Console.WriteLine(array[1]);

            Console.WriteLine(array[2]);

            Console.WriteLine(array[3]);

            Console.WriteLine(array[4]);

            Console.WriteLine("Press Any Key to Exit..");

            Console.ReadLine();

        }

    }

}

If you observe above example, we declared and initialized an array with 5 elements and we are accessing an array elements using index values.

 

When we execute above c# program, we will get the result like as shown below.

 

C# Arrays Example Result

 

If you observe above result, we are able to access an array elements using index numbers based on our requirements.

C# Access Array Elements with For Loop

In c#, by using for loop we can iterate through an array elements and access the values of an array with length property.

 

Following is the example of accessing an array elements using for loop in c# programming language.

 

using System;

 

namespace Tutlane

{

    class Program

    {

        static void Main(string[] args)

        {

            int[] array = new int[5] { 1, 2, 3, 4, 5 };

            for (int i = 0; i < array.Length; i++)

            {

                Console.WriteLine(array[i]);

            }

            Console.WriteLine("Press Any Key to Exit..");

            Console.ReadLine();

        }

    }

}

If you observe above example, we looping through an array elements with for loop to access an array elements based on our requirements.

 

When we execute above c# program, we will get the result like as shown below.

 

C# Access Array Elements with For Loop Example Result

 

If you observe above result, we are able to loop through an elements in array with for loop and print array values based on our requirements.

C# Access Array Elements with Foreach Loop

In c#, same as for loop we can use foreach loop to iterate through an array elements and access the values of an array based on our requirements.

 

Following is the example of accessing an array elements using foreach loop in c# programming language.

 

using System;

 

namespace Tutlane

{

    class Program

    {

        static void Main(string[] args)

        {

            int[] array = new int[5] { 1, 2, 3, 4, 5 };

            foreach(int i in array)

            {

                Console.WriteLine(i);

            }

            Console.WriteLine("Press Any Key to Exit..");

            Console.ReadLine();

        }

    }

}

If you observe above example, we looping through an array elements with foreach loop to access an array elements based on our requirements.

 

When we execute above c# program, we will get the result like as shown below.

 

C# Access Array Elements with Foreach Loop Example Result

 

If you observe above result, we are able to loop through an elements in array with foreach loop and print array values based on our requirements.

 

This is how we can access an array elements in c# programming language based on our requirements.

C# Array Types

In c#, we have a different type of arrays available, those are

 

In this chapter, whatever the arrays we used, all are single dimensional arrays. In next chapters, we will learn about multi-dimensional and jagged arrays in detailed manner.

C# Array Class

In c#, we have a class called Array and it will act as a base class for all the arrays in common language runtime (CLR). The Array class provides a methods for creating, manipulating, searching and sorting an arrays.

 

For example, by using Sort or Copy methods of Array class we can sort the elements of an array and copy the elements of one array to another based on our requirements.

 

Following is the example of using an Array class to sort or filter or reverse array elements in c# programming language.

 

using System;

 

namespace Tutlane

{

    class Program

    {

        static void Main(string[] args)

        {

            int[] array = new int[5] { 1, 4, 2, 3, 5 };

            Console.WriteLine("---Initial Array Elements---");

            foreach (int i in array)

            {

                Console.WriteLine(i);

            }

            Array.Sort(array);

            Console.WriteLine("---Elements After Sort---");

            foreach (int i in array)

            {

                Console.WriteLine(i);

            }

            Array.Reverse(array);

            Console.WriteLine("---Elements After Reverse---");

            foreach (int i in array)

            {

                Console.WriteLine(i);

            }

            Console.WriteLine("Press Any Key to Exit..");

            Console.ReadLine();

        }

    }

}

If you observe above example, we sorting and changing the order of array elements using Sort and Reverse methods of an Array class.

 

When we execute above c# program, we will get the result like as shown below.

 

C# Array Class Example Result

 

If you observe above result, we sorted the elements of an array and changed the order of an array elements using Array class based on our requirements.

 

This is how we can use required methods of Array class in our applications to implement required functionality.