Arrays in C#

Arrays in C# are fixed-size sequences of elements of a specific type. While Lists are more commonly used in typical C# code, arrays are useful in certain scenarios.

using System;

class Program
{
    static void Main()
    {
        // Here we create an array 'a' that will hold exactly 5 integers.
        // By default, an array is zero-valued, which for integers means 0s.
        int[] a = new int[5];
        Console.WriteLine("emp: " + string.Join(" ", a));

        // We can set a value at an index using the array[index] = value syntax,
        // and get a value with array[index].
        a[4] = 100;
        Console.WriteLine("set: " + string.Join(" ", a));
        Console.WriteLine("get: " + a[4]);

        // The Length property returns the length of an array.
        Console.WriteLine("len: " + a.Length);

        // Use this syntax to declare and initialize an array in one line.
        int[] b = new int[] { 1, 2, 3, 4, 5 };
        Console.WriteLine("dcl: " + string.Join(" ", b));

        // In C#, you can use array initializer syntax to create and initialize an array.
        int[] c = { 1, 2, 3, 4, 5 };
        Console.WriteLine("dcl: " + string.Join(" ", c));

        // C# doesn't have a direct equivalent to Go's ... syntax for array initialization.
        // However, you can achieve similar results using array initialization with specific indices.
        int[] d = new int[5];
        d[0] = 100;
        d[3] = 400;
        d[4] = 500;
        Console.WriteLine("idx: " + string.Join(" ", d));

        // Array types are one-dimensional, but you can create multi-dimensional arrays.
        int[,] twoD = new int[2, 3];
        for (int i = 0; i < 2; i++)
        {
            for (int j = 0; j < 3; j++)
            {
                twoD[i, j] = i + j;
            }
        }
        Console.WriteLine("2d: " + string.Join(" ", twoD.Cast<int>()));

        // You can create and initialize multi-dimensional arrays at once too.
        int[,] twoD2 = new int[,]
        {
            { 1, 2, 3 },
            { 1, 2, 3 }
        };
        Console.WriteLine("2d: " + string.Join(" ", twoD2.Cast<int>()));
    }
}

When you run this program, you’ll see output similar to:

emp: 0 0 0 0 0
set: 0 0 0 0 100
get: 100
len: 5
dcl: 1 2 3 4 5
dcl: 1 2 3 4 5
idx: 100 0 0 400 500
2d: 0 1 2 1 2 3
2d: 1 2 3 1 2 3

Note that arrays in C# are printed as space-separated values when using string.Join(). The Cast<int>() method is used to flatten the 2D array for printing.

C# arrays are zero-indexed, fixed in size, and can be single-dimensional, multidimensional, or jagged. While they’re useful in certain scenarios, for more flexibility, consider using collections like List<T> from the System.Collections.Generic namespace.