Arrays in C#

Arrays in C# with Examples

In this article, I am going to discuss the Arrays in C# with different types of examples. Before understanding the arrays in C#, let us first discuss why we need arrays in programming.

As we know a primitive type variable such as int, double can hold only a single value at any given point of time. For example, int no = 10;. Here the variable “no” holds a value of 10. As per your business requirement, if you want to store 100 integer values, then you may create 100 integer variables which are not a good programming approach as it will take lots of time as well as your code becomes bigger. So to overcome the above problems, Arrays in C# are introduced.

What is an Array in C#?

In simple words, we can define an array as a collection of similar type of values which are stored in sequential order i.e. they stored in a contiguous memory location.

Types of Arrays in C#:

C# supports 2 types of arrays. They are as follows:

  1. Single dimensional array’
  2. Multi-dimensional array

In the Single dimensional array, the data is arranged in the form of a row whereas in the Multi-dimensional arrays in C# the data is arranged in the form of rows and columns. Again the multi-dimensional arrays are of two types

  1. Jagged array: whose rows and columns are not equal
  2. Rectangular array: whose rows and columns are equal

We can access the values of an array using the index positions whereas the array index starts from 0 that means the first item of an array will be stored at 0th position and the position of the last item of an array will be the total number of the item – 1.

Arrays in C# Memory Representation:

Please have a look at the following diagram:

Arrays in C# Memory Representation

As you can see in the above diagram, we have an integer array with 10 elements. The array index is starting from 0, which stores the first element of the array. As the array contains 10 elements, so the last index position will be 9. The Array values or elements are stored sequentially in the memory i.e. contiguous memory allocation and this is the reason why it performs faster.

In C#, the arrays can be declared as fixed length or dynamic. The Fixed length array means we can store a fixed number of elements while in case of the dynamic array, the size automatically increases as we add new items into the array.

Note: The Arrays in C# are reference types which are derived from the System.Array class.

Can we use a foreach loop to iterate on arrays in C#?

Yes. Since the arrays in C# are derived from the System.Array class which implements the IEnumerable, so we can use the foreach loop to iterate on arrays in C#.  We this keep in mind let us discuss the arrays in C# with examples.

One Dimensional Array in C# with Examples:

The array which stores the data in the form of rows in sequential order is called one-dimensional array in C#. The syntax for creating a one-dimensional array in C# is given below.

One Dimensional Array Syntax in C#

As you can see in the above image, we can initialize an array in C# either by using the new keyword or using the argument values.

Let’s understand the one-dimensional array in C# with an example.
namespace ArayDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            //Creating an array with size 6
            int[] arr = new int[6];
            
            //accessing array values using loop
            //Here it will display the default values
            //as we are not assigning any values
            for (int i = 0; i < 6; i++)
            {
                Console.Write(arr[i] + " ");
            }

            Console.WriteLine();
            int a = 0;

            //Here we are assigning values to array using for loop
            for (int i = 0; i < 6; i++)
            {
                a += 10;
                arr[i] = a;
            }

            //accessing array values using foreach loop
            foreach (int i in arr)
            {
                Console.Write(i + " ");
            }

            Console.ReadKey();
        }
    }
}
OUTPUT:

Arrays in C#

For each loop in C#:

This loop is specially designed in C# for accessing the values from a collection like an array. When we use a foreach loop for accessing the values of an array or collection, we only require to handover the array or collection to the loop which does not require any initialization, condition or iteration. The loop itself start its execution by providing access to each and every element present in the array or collection starting from the first up to the last element in sequential order.

What is the difference between for loop and for each loop in C# to access array values?

In the case of for loop in C#, the loop variable refers to the index of an array whereas, in the case of a foreach loop, the loop variable refers to the values of the array.

Irrespective of the values stored in the array, the loop variable must be of type int in case of for loop. The reason for this is, here the loop variable is referring to the index position of the array.  Coming to the foreach loop, the data type of the loop variable must be the same as the type of the values stored in the array. For example, if you have a string array then the loop variable must be of type string in case of the foreach loop in C#.

The most important point that you need to keep in mind is that the for loop in C# can be used both for accessing values from an array as well as assigning values to an array whereas the foreach loop in C# can only be used for accessing the values from an array but not for assigning values into an array.

What is the Array class in C#?

The Array class is a predefined class which is defined inside the System namespaces. This class is work as the base class for all the arrays in C#. The Array class provides a set of members (methods and properties) to work with the arrays such as creating, manipulating, searching and sorting the elements of an array. The definition of the array class is gen below.

Array class definition in C#The Array class in C# is not a part of the System.Collections namespace, it is a part of the System namespace. But still, we considered it as a collection because it is based on the IList interface.

The Array class provides the following methods and properties:

  1. Sort(<array>)
  2. Reverse (<array>)
  3. Copy (src, dest, n)
  4. GetLength(int)
  5. Length 
Let’s see an example for understanding the above functions and properties of the Array Class in C#.
namespace ArayDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            //Declaring an array
            int[] arr = { 17, 23, 4, 59, 27, 36, 96, 9, 1, 3 };

            //Printing the array elements
            Console.WriteLine("The Array Contains the Below Elements:");
            for (int i = 0; i < arr.Length; i++)
            {
                Console.Write(arr[i] + " ");
            }
            Console.WriteLine();

            //Sorting the array elements
            Array.Sort(arr);

            //Printing the array elements after sorting
            Console.WriteLine("The Array Elements After Sorting:");
            foreach (int i in arr)
            {
                Console.Write(i + " ");
            }
            Console.WriteLine();

            //Reversing the array elements
            Array.Reverse(arr);

            //Printing the array elements in reverse order
            Console.WriteLine("The Array Elements in the Reverse Order :");
            foreach (int i in arr)
            {
                Console.Write(i + " ");
            }
            Console.WriteLine();

            //Creating a new array
            int[] brr = new int[10];

            //Copying some of the elements from old array to new array
            Console.WriteLine("The new array elements:");
            Array.Copy(arr, brr, 5);
            //We declare the array with size 10. we copy only 5 elements. so the rest
            //5 elements will take the default value. In this array, it will take 0
            foreach (int i in brr)
            {
                Console.Write(i + " ");
            }
            Console.ReadKey();
        }
    }
}
OUTPUT:

Arrays in C#

Implicitly Typed Arrays in C#:

When we declare an array by using the “var” keyword then such type of arrays are called implicitly typed array in C#.

Example: var arr = new[] {10, 20, 30 , 40, 50};

Let us see an example for understanding the implicitly typed array in C#.
namespace ArayDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            var arr = new[] { 17, 23, 4, 59, 27, 36, 96, 9, 1, 3 };
            for (int i = 0; i < arr.Length; i++)
            {
                Console.Write(arr[i] + " ");
            }
            Console.ReadKey();
        }
    }
}
OUTPUT:

Array in C#

In the next article, I am going to discuss the two-dimensional array in C# with examples.

SUMMARY:

In this article, I try to explain Arrays in C# with examples. I hope this article will help you with your need. I would like to have your feedback. Please post your feedback, question, or comments about this article.

Leave a Reply

Your email address will not be published. Required fields are marked *