Array Manipulations in C#: Part 1


Introduction

Arrays in C# look like they do in C/C++ but basically a C# Array is derived from the base class System.Array. An Array is an un-ordered sequence of elements. All the elements in an Array have the same type unlike the fields in a structure or class which can have different types. The elements of an Array live in a contiguous block of memory and are accessed using an integer index unlike fields in a structure or class which are accessed by name. Normally in C# the Array index starts with 0 but it is possible to have an Array with an arbitrary lower bound using the static method CreateInstance() of System.Array.


Arrays can be single or multidimensional and the declaration would be as follows for a single dimensional:

Declaration of Array

int[] x = new int[12];


In the above statement I have declared an integer type Array named x having 12 cells. Now to assign a value in them
 

x[0] = 5;

x[1] = 10;

::::::::::

X[11] = 7;


Please note; index values start from 0 (are zero-based) and (for that Array) ends at 11 for the 12 integer type cells. Let's have one more example and some discussion.


int[] b = {5,7,18,15};


In the above example, the new keyword is missing but the statement is still valid. Why it is still valid is that for new just remember an Array can be used with or without having its instance. Keep on reading, you will find more on this.

 

    class Program

    {

        static void Main()

        {

            int[] b = { 5, 7, 18, 15 };

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

            {

                Console.WriteLine(b[i]);

            }

            Console.ReadKey();

        }

    }


Actually, Arrays are reference types regardless of the type of their elements. That means that an Array variable refers to a contiguous block of memory holding Array elements on the heap just like a class variable that refers to an object on the heap. This contiguous block of memory does not hold its Array elements directly on the stack as any structure (struct) does. Recall that when we declare a class variable, memory is not allocated for the object until we create its instance by using the new keyword. Here Array follows the same rules. When we declare an Array variable we do not declare its size at that time. We specify its size only when creating its instance and to create instance we use new keyword followed by element type, followed by size of the Array between square brackets. One more thing we should note here is that Array initializes its default values automatically depending upon the type of value like, 0 for numeric, null for reference (like string) and true/false for Boolean. Let's see some examples here.


int size = int.Parse((Console.ReadLine());  //assume size=4

int[] x = new int[size];
 

Or
 

int[] x = new int[4];

 

Let's see one example on strings.
 

int size = int.Parse(Console.ReadLine());  //assume size=4

string[] str = new string[size];

 

Or
 

string[] str = new string[4];

Initialization of Array

As we have discussed above, when we create an instance of Array, all the elements are automatically initialized to its default value depending upon their type. Actually we always modify Array values. We can modify behavior and initialize the elements of an Array to a specific value if we prefer. We do this by providing a comma separated list of values between a pair of braces. For example:
 

int[] x = new int[4]{ 5, 7, 18, 15 };

 

One more way we have to assign values implicitly:

 

int[] x = new int[4];

x[0] = 5;

x[1] = 7;

x[2] = 18;

x[3] = 15;

 

Values of Array can be calculated at run-time also and stored in it. For example:

 

Random arVal = new Random();

int[] x = new int[4]{ arVal.Next(), arVal.Next(), arVal.Next(), arVal.Next() );
 

Remember to match the size of an Array with the number of values, otherwise we will get compile time errors.

 

Let's see one example using string.

 

string[] str = new string[2]{ "abhimanyu", "kumar" };

 

Or

 

string[] str = new string[2];

str[0] = "abhimanyu";

str[1] = "kumar";

 

C# also supports var type declaration of Array and this is bit similar to JavaScript type Arrays. Let's look at an example and talk about it.

 

var myFrndz = new[]{ "Deepak", "Rohit", "Rahul", "Manish" };

 

In the above example, the C# compiler determines that the myFrndz variable is an Array of strings and it is worth pointing out some strange syntax. We omitted the square brackets from the type and myFrndz variable is declared simply as a var and not even var[]. That's okay in C# but keep in mind or be ensured that all the initializers have the same type or not, it should be. The example given below will produce a compile time error only because it does not have the same type.
 

var myFrndz = new[]{ 23, 23.5, "Rahul", "Manish" };
 

In some cases the compiler will convert elements to a different type. In the example given below, both integer and double values are provided but thanks to the C# compiler it which manages or say converts all for us.

 

var num = new[]{ 5, 7, 12.5, 12.6 };

Accessing an Array

To access an individual Array element we must provide an index value indicating which element is required. Look, if you have declared an Array having 4 elements then we can ask for an element with an index of 0 to 3; if we cross this bound then will get errors.
 

int[] x = new int[4]{ 5, 7, 18, 15 };

Console.WriteLine(x[index_value]);  //index value will be 0 to 3

 

Look at the program below which iterates through each element of an Array.
 

    class Program

    {

        static void Main()

        {

 

            int[] x = new int[4] { 5, 7, 18, 15 };

 

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

            {

                Console.WriteLine(x[i]);

            }

            Console.ReadKey();

        }

    }

Copy Array Variable and Instance

Copying of an Array variable and instance has different meanings. We made lots of discussions over Arrays and one of them that is Arrays are reference types and an Array is an instance of the System.Array class.

Copy Array Variable

An Array variable is a reference to an Array instance, which means that when we copy an Array, we actually end up with two references to the same Array instance.
 

int[] x = { 5, 7, 12, 15 };

int[] cpX = x;

 

In the above example, if we modify the value of x[1] then changes will also be visible by cpX[1]. Look at a simple program which explains all things about copying Array variables.
 

    class Program

    {

        static void Main()

        {

 

            int[] x = { 5, 7, 12, 15 };

            int[] cpX = x;

 

            //modify the value of index 1

            Console.WriteLine("Enter to modify the index 1 of cpX Array.");

            cpX[1] = int.Parse(Console.ReadLine());

 

            //checking x array that changing effects or not

            Console.WriteLine("Modified in cpX array above, now checking x array.");

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

            {

                Console.WriteLine(x[i]);

            }

            Console.ReadKey();

        }

    }
 

Output:

 

Array

Copy Array Instance

If we want to make a copy of the Array instance, do it this way. 

 

    class Program

    {

        static void Main()

        {

 

            int[] x = { 5, 7, 12, 15 };

            int[] cpX = new int[x.Length];

 

            //display primary values

            Console.WriteLine("Primary value of x array.");

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

            {

                Console.WriteLine(x[i]);

            }

 

            //copying

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

            {

                cpX[i] = x[i];

            }

 

            //modify the value

            Console.WriteLine("Enter one value for index 1 of cpX array.");

            cpX[1] = int.Parse(Console.ReadLine());

 

            //check the value of x array

            Console.WriteLine("Check values of x array.");

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

            {

                Console.WriteLine(x[i]);

            }

 

            //check the value of cpX array

            Console.WriteLine("Check values of cpX array.");

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

            {

                Console.WriteLine(cpX[i]);

            }

 

            Console.ReadKey();

        }

    }
 

Output:

 

Array
 

We have seen some System.Array methods that can copy an Array for us. I will describe more in future parts, with some hot examples and programs.


Find Part-2 here.

 

Thanks for reading.

Up Next
    Ebook Download
    View all
    Learn
    View all