c sharp Logo

C# Arrays


C# Arrays

Arrays are a fundamental data structure in C# used to store a collection of elements of the same data type. They provide a structured way to group and manage related data, allowing efficient access and manipulation of individual elements or the entire array.

Declaring and Initializing Arrays

Arrays are declared using the [] brackets, specifying the data type and the array size:

int[] numbers = new int[5]; // Declare an array of 5 integers

string[] names = { "Alice", "Bob", "Charlie" }; // Initialize an array with values

 

Accessing Array Elements

Individual array elements are accessed using their index, which starts from 0:

int firstNumber = numbers[0]; // Access the first element of the numbers array

string thirdName = names[2]; // Access the third element of the names array

 

Looping through Arrays

The for loop is commonly used to iterate through the elements of an array:

for (int i = 0; i < numbers.Length; i++) {

  Console.WriteLine(numbers[i]);

}

 

Sorting Arrays

The Array.Sort() method sorts the elements of an array in ascending order:

Array.Sort(numbers); // Sort the numbers array in ascending order

 

Multidimensional Arrays

Multidimensional arrays are arrays that have multiple dimensions, allowing the storage of data in a more structured and organized manner. They are declared using multiple sets of square brackets, specifying the number of dimensions and the array size for each dimension:

int[,,] threeDimensionalArray = new int[3, 4, 2]; // Declare a three-dimensional array

 

Multidimensional arrays are accessed using multiple indices, one for each dimension:

int value = threeDimensionalArray[2, 1, 0]; // Access an element in the three-dimensional array

 

Conclusion

Arrays are versatile and powerful data structures that are essential for many programming tasks in C#. They provide efficient storage and manipulation of data, enabling the organization and processing of collections of related elements. Understanding arrays is crucial for developing effective and efficient C# programs.