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.
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;
dataType: Specifies the type of elements that the array will store (e.g., int, string, bool, or a custom class).[]: Indicates that the variable is an array.arrayName: The name of the array variable.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.
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#.
new KeywordThe 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];
arraySize: Specifies the number of elements the array can hold. This value must be a non-negative integer.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:
int, float, double): 0