Arrays in C#

Arrays in C# with Examples

In this article, I am going to discuss the Arrays in C# with examples. It is one of the important concepts in programming languages. Arrays are there from our traditional programming languages such as C, C++ and are also available in C#. As part of this article, we are going to discuss the following pointers.

  1. Why do we need arrays in programming?
  2. What is an Array in C#?
  3. Types of Arrays in C#.
  4. Understanding the memory representation of the array in C#.
  5. One Dimensional Array in C# with Examples
  6. What is the difference between for loop and for each loop in C# to access array values?
  7. What is the Array class in C#?
  8. Understanding the Array class methods and properties.
  9. What is Implicitly Type Array in C#?
Why do 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 in 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 need to create 100 integer variables which is 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 types of values that are stored in sequential order i.e. they are 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 which means the first item of an array will be stored at the 0th position and the position of the last item of an array will be the total number of the item – 1.

Memory Representation of Arrays in C#:

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 location 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 the case of the dynamic array, the size of the array automatically increases as we add new items into the array.

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

Can we use a for each 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 for-each loop to iterate on arrays in C#.  

One Dimensional Array in C# with Examples:

The array which stores the data in the form of rows in a sequential order is called a 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.

One-dimensional Array Example in C#.

In the below example, first, we create an array with size 6. To check what default values an array in c# store, without initializing the array, we are printing the values on the console using a for loop. Then again, using a for loop we are assigning the elements to the array. Finally, we are accessing the array elements and printing the values on the console using a for each loop.

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: As you can see in the below output, the default values 0, will store for integer type array.

Arrays in C#

In this example, we have used a special loop called for each loop to access the array elements in C#. Let us first understand what this for each loop is and then we will see the difference between for and for each loop in C#.

For each loop in C#:

This for each loop is specially designed in C# for accessing the values from a collection like an array. When we use a for-each loop for accessing the values of an array or collection, we only require to hand over the array or collection to the loop which does not require any initialization, condition, or iteration. The loop itself starts 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 for-each 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 for-each 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 for-each 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 for-each 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 that is defined inside the System namespaces. This class is working 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, reversing, and sorting the elements of an array, etc. The definition of the Array class in C# is gen below.

Array class 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 Implements the IList interface. The Array class provides the following methods and properties:

  1. Sort(<array>): Sorting the array elements
  2. Reverse (<array>): Reversing the array elements
  3. Copy (src, dest, n): Copying some of the elements or all elements from the old array to the new array
  4. GetLength(int): A 32-bit integer that represents the number of elements in the specified dimension.
  5. Length: It Returns the total number of elements in all the dimensions of the Array; zero if there are no elements in the array. 
Example: Array class Methods and Properties in C#

Let’s see an example for understanding the Method and Properties of the Array class in C#.

using System;
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.WriteLine();
            Console.WriteLine("brr Array Length :" + brr.Length);
            Console.WriteLine("brr Array Length :" + brr.GetLength(0));
            Console.ReadKey();
        }
    }
}
Output:

Array Class Method and Properties in C# with Examples

Understanding the Implicitly Typed Arrays in C#:

When we declare an array by using the “var” keyword then such types of arrays are called implicitly typed arrays 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:

Understanding Implicilt Typed Array in C#

In the next article, I am going to discuss the two-dimensional array in C# with examples. Here, in this article, I try to explain Arrays in C# with examples. I hope this article will help you with your needs. 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 *