Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to access elements from an array in C#?
Arrays in C# are collections of elements that can be accessed using an index. Array indexing starts from 0, meaning the first element is at index 0, the second at index 1, and so on.
Syntax
Following is the syntax for accessing array elements by index −
arrayName[index]
Following is the syntax for declaring and initializing an array −
dataType[] arrayName = new dataType[size] {element1, element2, element3};
Using Index to Access Elements
Each element in an array has a specific position called an index. You can access any element by specifying its index in square brackets −
using System;
class Program {
static void Main() {
int[] prices = new int[3] {99, 92, 95};
// Accessing individual elements
Console.WriteLine("First element (index 0): " + prices[0]);
Console.WriteLine("Second element (index 1): " + prices[1]);
Console.WriteLine("Third element (index 2): " + prices[2]);
}
}
The output of the above code is −
First element (index 0): 99 Second element (index 1): 92 Third element (index 2): 95
Using Loops to Access All Elements
You can use a loop to access all elements in an array sequentially −
using System;
class Program {
static void Main() {
int[] prices = new int[3] {99, 92, 95};
// Using for loop to access all elements
for (int i = 0; i
The output of the above code is −
Price of Product[0] = 99
Price of Product[1] = 92
Price of Product[2] = 95
Product 3rd price: 95
Using foreach Loop
The foreach loop provides a simpler way to iterate through all array elements without using indexes −
using System;
class Program {
static void Main() {
string[] fruits = {"Apple", "Banana", "Orange", "Mango"};
Console.WriteLine("All fruits in the array:");
foreach (string fruit in fruits) {
Console.WriteLine("- " + fruit);
}
}
}
The output of the above code is −
All fruits in the array:
- Apple
- Banana
- Orange
- Mango
Key Points
-
Array indexing starts from 0, not 1.
-
Use
arrayName[index]to access elements at specific positions. -
Use
arrayName.Lengthproperty to get the total number of elements. -
Accessing an index beyond the array bounds will throw an
IndexOutOfRangeException.
Conclusion
Accessing array elements in C# is straightforward using square bracket notation with the element's index. You can access individual elements directly or use loops like for and foreach to process all elements efficiently.
