C# Arrays


This entry is part 2 of 8 in the series C# Complex Types

There are two types of arrays, single dimension arrays and multidimension arrays. Arrays are similar to variables, but can hold more than one value. An array represents a fixed number of variables of a particular type. In the second line of code below we are using the object initialization syntax to initialize the values in the array upon declaration. We have two types of arrays under the multidimensional category: rectangular and jagged. Below is an example of a single dimension array.

Object Initialization Syntax

C# 3.0 (.NET 3.5) introduced Object Initializer Syntax, a new way to initialize an object of a class or collection. Object initializers allow you to assign values to the fields or properties at the time of creating an object without invoking a constructor.

var numbers = new int[5];
var numbers = new int[5] {1, 2, 3, 4, 5};

We can declare a two dimensional rectangular array. In this array, there are 3 rows and 5 columns. Rows-Columns. If you want to access an element in the array you use the square brackets. Array indexes are zero-based.

var matrix = new int[3, 5];
var matrix = new int[3, 5] {
   {1, 2, 3, 4, 5},
   {6, 7, 8, 9, 10},
   {11, 12, 13, 14, 15}
}
var element = matrix[0, 0];

Think of jagged arrays as arrays of arrays. Suppose we need to have 3 rows. The number of columns varies. How do we handle that? Suppose our first row has 3 elements, the second row has 5 elements and the third row has 2 elements. What would the code look like?

var array = new int[3][];
array[0] = new int[4];
array[0] = new int[5];
array[0] = new int[2];
// to access an element we need 2 sets of square brackets
array[0][0] = 1;

DataType[ ] ArrayName = { Comma Separated Values } // Array of any size

DataType[] ArrayName = new DataType[3] {Command Separated Values } //Expects 3 values

Here is an example in C#.

class Program  { // Foreach with Arrays
    static void Main(string[] args) {
        int myInt = 0;
        string[] friendNames = { "Sam", "Jack", "John" };
        WriteLine($"{friendNames.Length} of my friends:");
        foreach (string friendN in friendNames)
        {  // foreach gives READ-ONLY access
            WriteLine(friendN);
            ++myInt;  // just a counter
        }
        // or you can use a for loop:
        for (int i = 0; i < friendNames.Length; i++) {
            WriteLine(friendNames[i]); }
        ReadKey();
    }
}

foreach is discussed in the post C# foreach Loop.

Series Navigation<< C# Complex Types IntroductionC# Enumerations >>