Arrays in C#
Arrays in C#
In C#, arrays are a collection of variables that share the same data type. They provide a convenient way to store and manipulate multiple values under a single name.
Types of Arrays in C#
-
Single-Dimensional Arrays:
- A linear collection of elements, accessed using a single index.
- Declaration:
C#
int[] numbers = new int[5]; // Declares an array of 5 integers - Initialization:
C#
int[] numbers = { 1, 2, 3, 4, 5 }; // Initializes with values - Access:
C#
int firstNumber = numbers[0]; // Access the first element
-
Multi-Dimensional Arrays:
Key Points to Remember:
- Array Indexing: Array elements are accessed using zero-based indexing. The first element is at index 0, the second at index 1, and
1 so on. - Array Bounds Checking: C# performs bounds checking to prevent accessing elements outside the array's range. Out-of-bounds access will result in an
IndexOutOfRangeException. - Array Length: The
Lengthproperty of an array provides the total number of elements in the array. - Array Methods: C# provides various methods to work with arrays, such as
Sort,Reverse, andIndexOf. - Jagged Arrays: Arrays of arrays, where each element can have a different length.
Example: Single-Dimensional Array
C#
int[] numbers = { 10, 20, 30, 40, 50 };
// Accessing elements
Console.WriteLine(numbers[0]); // Output: 10
Console.WriteLine(numbers[2]); // Output: 30
// Modifying elements
numbers[1] = 25;
// Iterating through the array
foreach (int number in numbers)
{
Console.WriteLine(number);
}
Example: Two-Dimensional Array
C#
int[,] matrix = { { 1, 2, 3 }, { 4, 5, 6 } };
// Accessing elements
Console.WriteLine(matrix[0, 1]); // Output: 2
// Iterating through the array
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 3; j++)
{
Console.Write(matrix[i, j] + " ");
}
Console.WriteLine();
}
Additional Considerations:
- Array Initialization: You can initialize arrays using an initializer list or by assigning values to individual elements.
- Array Copying: You can create a copy of an array using the
Array.Copymethod or by using theClonemethod. - Array Sorting and Searching: Use the
Array.Sortmethod to sort an array and theArray.BinarySearchmethod to search for a specific element.
By understanding these concepts, you can effectively use arrays in your C# programs to store and manipulate data efficiently.
Would you like to delve deeper into a specific aspect of arrays, such as jagged arrays, multidimensional arrays, or array methods?
Comments
Post a Comment