C sharp - Array creation,declaration and initialization
In C#, an array is a data structure that holds a fixed number of values of the same type.
1. Declaration
To declare an array, specify the type of elements followed by square brackets:
int[] numbers; // Declares an array of integers
This only declares the array variable — no memory is allocated yet.
2. Creation (Instantiation)
To create an array, use the new
keyword:
numbers = new int[5]; // Creates an array of 5 integers
This creates memory space for 5 integers (default-initialized to 0).
3. Initialization
You can assign values to array elements one by one:
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
numbers[3] = 40;
numbers[4] = 50;
Or, use declaration + initialization in one line:
int[] numbers = new int[] { 10, 20, 30, 40, 50 };
Or even shorter:
int[] numbers = { 10, 20, 30, 40, 50 };