Array Manipulations in C# - Part 1


Introduction

Array in C# looks like C/C++ but basically C# array are derived from 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 by 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 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 single dimensional:

Declaration of Array

int[] x = new int[12];

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

x[0] = 5;
x[1] = 10;
::::::::::
X[11] = 7;

Please note index values starts from 0 and ends at 11 for 12 integer type cells. Let’s have one more example and some discussion.

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

In above example, new keyword is missing but it is still valid. Why it is still valid, for new just remember 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. Means an array variable refers to a contiguous block of memory holding array elements on the heap just like 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 when we declare a class variable memory is not allocated for the object until we create its instance by using new keyword. Here array follow 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, array initializes its default values automatically depending upon 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 instance of array, all the elements are automatically initialized to its default value depending upon their type. Actually we always modifies array values. We can modify behavior and initialize the elements of an array to specific values if we prefer. We achieve 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 here 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 array and number of values otherwise we will get compile time errors.

Let’s see one example on 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 example and talk about this.

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

In above example, 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 var and not even var[]. That's okay in C# but keep in mind or be ensure that all the initializer has the same type or not, it should be. The example given below will release compile time error only because it has not same type.

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

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

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

Accessing Array

To access an individual array element we must provide an index value indicating which element require. Look if you have declared an array having 4 size then we can ask for 0 to 3 index, 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 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 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 array is instance of System.Array class.

Copy Array Variable

Array variable contains reference to an array instance means 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 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:


Copy Array Instance

If we want to make a copy of the array instance, use 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:


We have some System.Array methods which copies the array for us. Will talk of them in coming part. Will see some hot examples, programs in next part.

Thanks for reading.

Comments

Popular posts from this blog

Customize User's Profile in ASP.NET Identity System

Migrating database from ASP.NET Identity to ASP.NET Core Identity