What are Arrays
Arrays are a fundamental concept in programming and are used in almost every type of code you write. In C#, arrays are a type of data structure that can store a fixed-size sequential collection of elements of the same type. They are used to store collections of data, but they are more useful when you want to work with a specific, fixed number of elements.
What is an Array?
An array is a collection of elements identified by index or key. In C#, arrays can be declared as one-dimensional (1D), multi-dimensional or jagged. One-dimensional arrays are the simplest form and the most commonly used.
Declaring Arrays
To declare an array in C#, you use the following syntax:
datatype[] arrayName;
For example:
int[] myArray;
In this example, we've declared an array named myArray
that will store integers (int
). However, at this point, the array doesn’t contain any elements.
Initializing Arrays
To initialize an array, you can use the new
keyword followed by the data type of the array and square brackets containing the length of the array. Here's an example:
int[] myArray = new int[5];
In this example, myArray
is an array of integers that can hold five elements.
You can also initialize an array at the time of declaration with a set of values, like so:
int[] myArray = new int[] {1, 2, 3, 4, 5};
Or even simpler:
int[] myArray = {1, 2, 3, 4, 5};
Accessing Array Elements
You can access the elements in an array by referring to the index number. Array indexes in C# start at zero, which means the first element is at index 0, the second element is at index 1, and so forth. Here's an example:
int[] myArray = {1, 2, 3, 4, 5};
int firstElement = myArray[0]; // firstElement will be 1
Multi-Dimensional Arrays
C# supports multi-dimensional arrays. The simplest form of the multi-dimensional array is the two-dimensional array. Here's how you can declare a two-dimensional array:
int[,] my2DArray = new int[4, 2];
In this example, my2DArray
is a 2D array of integer type. It can hold 8 elements, i.e., 2 elements in 4 rows.
You can initialize a 2D array at time of declaration like this:
int[,] array = new int[3, 4] {
{ 1, 2, 3, 4 }, /* initializers for row indexed by 0 */
{ 5, 6, 7, 8 }, /* initializers for row indexed by 1 */
{ 9, 10, 11, 12 } /* initializers for row indexed by 2 */
};
Conclusion
Arrays in C# are very useful for storing multiple values in a single variable, which can condense and organize our code, making it more readable and efficient. They are particularly useful when you have a fixed number of elements that are of the same type, and you wish to iterate through them.