C# Initialize Array Example

In this source code example, we will demonstrate how to initialize an Array in C# with an example.

C# Initialize Array Example

Below C# program to declare and initialize a numerical array:
using System;

public class ArrayDemo
{
    public static void Main(string[] args)
    {
        int[] array = new int[5];
        
        array[0] = 1;
        array[1] = 2;
        array[2] = 3;
        array[3] = 4;
        array[4] = 5;
        
        for (int i = 0; i < array.Length; i++)
        {
            Console.WriteLine(array[i]);
        }
    }
}

Output:

1
2
3
4
5

We can declare and initialize an array in one statement:

using System;

public class ArrayDemo
{
    public static void Main(string[] args)
    {
        int[] array = new int[] { 2, 4, 5, 6, 7, 3, 2 };
        
        for (int i = 0; i < array.Length; i++)
        {
            Console.WriteLine(array[i]);
        }
    }
}

Output:

1
2
3
4
5



Comments