C# Accessing Array Elements
Array elements are accessed using their index, which starts at 0. You can read or modify elements by specifying the index inside square brackets.
Key Topics
1. Accessing Elements
Example: Reading Array Elements
string[] fruits = { "Apple", "Banana", "Cherry" };
Console.WriteLine(fruits[0]); // Outputs "Apple"
Console.WriteLine(fruits[1]); // Outputs "Banana"
Output:
Apple
Banana
Banana
2. Modifying Elements
Example: Changing Array Elements
fruits[2] = "Orange";
Console.WriteLine(fruits[2]); // Outputs "Orange"
Output:
Orange
3. Array Bounds
Attempting to access an index outside the bounds of the array will result in an IndexOutOfRangeException
.
Example: Out-of-Bounds Access
// This will throw an exception
Console.WriteLine(fruits[3]);
Explanation: Since the fruits
array has indices from 0 to 2, accessing fruits[3]
is invalid and will cause an error.
Key Takeaways
- Array indices start at 0.
- You can access and modify elements using their index.
- Be cautious of array bounds to avoid runtime exceptions.
- Understanding how to access elements is crucial for manipulating arrays.