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
Are arrays zero indexed in C#?
Yes, arrays are zero-indexed in C#. This means the first element of an array is stored at index 0, the second element at index 1, and so on. The relationship between array length and indexing follows a consistent pattern.
Array Length vs Index Range
-
If the array is empty, it has zero elements and length
0. -
If the array has one element at index
0, then it has length1. -
If the array has two elements at indexes
0and1, then it has length2. -
If the array has three elements at indexes
0,1, and2, then it has length3.
Syntax
Arrays in C# are accessed using square brackets with zero-based indexing −
dataType[] arrayName = new dataType[size]; arrayName[0] = value; // first element arrayName[1] = value; // second element arrayName[size-1] = value; // last element
Example
The following example demonstrates zero-based indexing by populating and displaying array elements −
using System;
namespace ArrayApplication {
class MyArray {
static void Main(string[] args) {
int[] n = new int[5];
int i, j;
/* begins from index 0 */
for (i = 0; i < 5; i++) {
n[i] = i + 5;
}
for (j = 0; j < 5; j++) {
Console.WriteLine("Element[{0}] = {1}", j, n[j]);
}
}
}
}
The output of the above code is −
Element[0] = 5 Element[1] = 6 Element[2] = 7 Element[3] = 8 Element[4] = 9
Accessing First and Last Elements
Here's an example showing how to access the first and last elements of an array −
using System;
class Program {
static void Main() {
string[] colors = {"Red", "Green", "Blue", "Yellow", "Orange"};
Console.WriteLine("Array length: " + colors.Length);
Console.WriteLine("First element (index 0): " + colors[0]);
Console.WriteLine("Last element (index {0}): {1}", colors.Length - 1, colors[colors.Length - 1]);
// Display all elements with their indexes
for (int i = 0; i < colors.Length; i++) {
Console.WriteLine("colors[{0}] = {1}", i, colors[i]);
}
}
}
The output of the above code is −
Array length: 5 First element (index 0): Red Last element (index 4): Orange colors[0] = Red colors[1] = Green colors[2] = Blue colors[3] = Yellow colors[4] = Orange
Key Points
-
The first element is always at index
0. -
The last element is at index
Length - 1. -
Accessing an index outside the range
[0, Length-1]throws anIndexOutOfRangeException. -
Array length is always one more than the highest valid index.
Conclusion
Arrays in C# are zero-indexed, meaning the first element is at index 0 and the last element is at index Length-1. Understanding this indexing system is fundamental for working with arrays and avoiding common off-by-one errors in C# programming.
