Arrays are fundamental data structures in C# used to store a fixed-size, sequential collection of elements of the same type. Understanding how to declare, initialize, and manipulate arrays is crucial for any C# developer, as they form the basis for more complex data structures and algorithms. This lesson will provide a comprehensive guide to working with arrays in C#, covering everything from basic syntax to more advanced manipulation techniques.

Declaring Arrays

In C#, declaring an array involves specifying the type of elements the array will hold and the name of the array variable. The syntax for declaring an array is as follows:

dataType[] arrayName;

Examples:

int[] numbers; // Declares an integer array named 'numbers'
string[] names; // Declares a string array named 'names'
bool[] flags;   // Declares a boolean array named 'flags'

These declarations only create the array variable; they don't allocate any memory to store the array elements. To allocate memory, you need to initialize the array.

Initializing Arrays

Array initialization involves allocating memory for the array and optionally assigning initial values to its elements. There are several ways to initialize an array in C#.

Using the new Keyword

The most common way to initialize an array is by using the new keyword, which allocates memory for a specified number of elements.

dataType[] arrayName = new dataType[arraySize];

Examples:

int[] numbers = new int[5]; // Creates an integer array with 5 elements
string[] names = new string[3]; // Creates a string array with 3 elements

When you initialize an array using the new keyword, the elements are automatically initialized to their default values: