Collections and Arrays in C#: Part 1

In this section, we will start by digging inside Arrays. Arrays are one of the most basic yet important spiece of C# Collections. One must have profound knowledge of arrays to understand various collection types better. In the following example, I have created a simple array for months of year. Any array declaration begins with [] bracket.

  1. namespace Collections    
  2. {    
  3.     class Program    
  4.     {    
  5.         static void Main(string[] args)    
  6.         {    
  7.             string[] monthsofYear =    
  8.             {    
  9.                 "Jan",    
  10.                 "Feb",    
  11.                 "Mar",    
  12.                 "Apr",    
  13.                 "May",    
  14.                 "Jun",    
  15.                 "Jul",    
  16.                 "Aug",    
  17.                 "Sep",    
  18.                 "Oct",    
  19.                 "Nov",    
  20.                 "Dec"    
  21.             };    
  22.         }    
  23.     }    
  24. }   
Now, when you run the preceding program in debugging mode, you will see that first it listed all the elements what I listed there and also in the same orde. In other words the arrays are an ordered list and are index based.

string

In the following script, I have added a couple of lines to illustrate the accessing of elements based on index.
  1. using System;    
  2.     
  3. namespace Collections    
  4. {    
  5.     class Program    
  6.     {    
  7.         static void Main(string[] args)    
  8.         {    
  9.             string[] monthsofYear =    
  10.             {    
  11.                 "Jan",    
  12.                 "Feb",    
  13.                 "Mar",    
  14.                 "Apr",    
  15.                 "May",    
  16.                 "Jun",    
  17.                 "Jul",    
  18.                 "Aug",    
  19.                 "Sep",    
  20.                 "Oct",    
  21.                 "Nov",    
  22.                 "Dec"    
  23.             };    
  24.             //accessing the element based on lookup    
  25.             //and then printing the value    
  26.             string march = monthsofYear[2];    
  27.             Console.WriteLine(march);    
  28.         }    
  29.     }    
  30. }  
element based on index

We can write a more generalized way to provide the user flexibility to enter the option as in the following code:
  1. using System;    
  2.     
  3. namespace Collections    
  4. {    
  5.     class Program    
  6.     {    
  7.         static void Main(string[] args)    
  8.         {    
  9.             string[] monthsofYear =    
  10.             {    
  11.                 "Jan",    
  12.                 "Feb",    
  13.                 "Mar",    
  14.                 "Apr",    
  15.                 "May",    
  16.                 "Jun",    
  17.                 "Jul",    
  18.                 "Aug",    
  19.                 "Sep",    
  20.                 "Oct",    
  21.                 "Nov",    
  22.                 "Dec"    
  23.             };    
  24.             Console.WriteLine( "Provide Index position to print the month!");    
  25.             int month = int.Parse(Console.ReadLine());    
  26.             Console.WriteLine(monthsofYear[month]);    
  27.         }    
  28.     }    
  29. }  
Now, when I see the output of this, it will look something like the following:

output
Also, if I need to enumerate through this array, then I will simply write one foreach loop as in the following code:
  1. using System;    
  2.     
  3. namespace Collections    
  4. {    
  5.     class Program    
  6.     {    
  7.         static void Main(string[] args)    
  8.         {    
  9.             string[] monthsofYear =    
  10.             {    
  11.                 "Jan",    
  12.                 "Feb",    
  13.                 "Mar",    
  14.                 "Apr",    
  15.                 "May",    
  16.                 "Jun",    
  17.                 "Jul",    
  18.                 "Aug",    
  19.                 "Sep",    
  20.                 "Oct",    
  21.                 "Nov",    
  22.                 "Dec"    
  23.             };    
  24.             foreach (var month in monthsofYear)    
  25.             {    
  26.                 Console.WriteLine(month);    
  27.             }    
  28.             Console.ReadLine();    
  29.         }    
  30.     }    
  31. }  
foreach loop

Until now, we have seen all readonly operations, now let's see a few write operations. The following snippet will simply go ahead and replace the items in the array. However, replace is equivalent to remove and add element to the array, but replace is quite efficient in doing the same job.
  1. using System;    
  2.     
  3. namespace Collections    
  4. {    
  5.     class Program    
  6.     {    
  7.         static void Main(string[] args)    
  8.         {    
  9.             string[] monthsofYear =    
  10.             {    
  11.                 "Jan",    
  12.                 "Feb",    
  13.                 "Mar",    
  14.                 "Apr",    
  15.                 "May",    
  16.                 "Jun",    
  17.                 "Jul",    
  18.                 "Aug",    
  19.                 "Sep",    
  20.                 "Oct",    
  21.                 "Nov",    
  22.                 "Dec"    
  23.             };    
  24.     
  25.             //Assigning diff value to existing one    
  26.             monthsofYear[2] = "Financial Month";    
  27.             foreach (var month in monthsofYear)    
  28.             {    
  29.                 Console.WriteLine(month);    
  30.             }    
  31.             Console.ReadLine();    
  32.         }    
  33.     }    
  34. }   
calander

Now, there are a few important points about arrays, like they have their own syntax in C#, you don't declare any other type using [] like we do with generics. Also, their strong typing is implemented at the CLR level itself. However, many collections like List<T> under the hood use arrays for their implementation. So, List<T> is basically dependent on T[].

One more point to note here is that arrays are reference types. So, the basic test to check this is by initializing some value and see it in the debugger, for value types it will be the default value for that variable and for a reference type it will be null as in the following screenshot:

initializing value

Arrays are reference types

However, since arrays are reference types, we can go ahead and create the array with new keyword as shown in the following example.
  1. //Creating an array of 5 elements   
  2.  int[] c = new int[5];   
Now, since I have initialized my array here with the int type, when I look at it, it will present me the default values as shown in the following screenshot:

initialized my array

However, in the following example, I have created and initialized the array as well.
  1. //create and initialize the array   
  2. int[] d = new int[5] { 1, 2, 3, 4, 5 };   
Now, when I see it in the debugger, it will present the following values.

debugger

One point to note here is that you can't initialize an array in the array constructor, .NET doesn't support that. The only thing you can do with array constructors is allocate the memory for it. However, the C# compiler is very flexible to understand the intent of the coder as shown in the following code snippet. Here, I have done an array initialization in various ways that are producing the same result.
  1. //Creating an array of 5 elements    
  2. int[] c = new int[5];    
  3. //create and initialize the array    
  4. int[] d = new int[5] { 1, 2, 3, 4, 5 };    
  5. //removed the redundant array size    
  6. int[] e = new int[] { 1, 2, 3, 4, 5 };    
  7. //used implicit typing using var    
  8. var f = new int[] { 1, 2, 3, 4, 5 };    
  9. //used explicit type on the left    
  10. int[] g = { 1, 2, 3, 4, 5 };  
Next look at enumerating the array, we have already seen the implicit style of enumeration using a foreach loop. However we can also step through explicitly and the easiest way is using a for loop. I have shown one sample snippet for that in the following code.
  1. //explicit looping    
  2.  for (int i = 0; i < monthsofYear.Length; i++)    
  3.  {    
  4.      Console.WriteLine(  monthsofYear[i]);    
  5.  }  

One more point to note here is that foreach is a readonly operation. In other words you can't set values to variables inside a foreach loop.

With this I would like to conclude the first section about arrays. In the next section, we'll do deep dive under the hood of arrays.


Similar Articles