C# Arrays
An array stores multiple values of the same type in a single variable, accessed by an index starting at 0. Arrays have a fixed size once created.
Arrays are useful when you need to work with a collection of related values, like a list of scores or names, and want fast, index-based access to each item.
type[] name = {value1, value2};
name[index];Declaring and accessing arrays
Arrays are declared with square brackets, like `int[] numbers = {1, 2, 3};`. Elements are accessed using their zero-based index, so numbers[0] is the first element.
Array properties and iteration
The Length property gives the number of elements. You can loop through an array using a for loop with the index, or a foreach loop for simpler iteration.
using System;
class Program {
static void Main() {
int[] numbers = { 10, 20, 30 };
Console.WriteLine(numbers[0]);
Console.WriteLine(numbers.Length);
}
}10
3numbers[0] accesses the first element, and Length gives the total count.
using System;
class Program {
static void Main() {
string[] fruits = { "apple", "banana", "cherry" };
for (int i = 0; i < fruits.Length; i++) {
Console.WriteLine(fruits[i]);
}
}
}apple
banana
cherryThe loop visits each index from 0 to Length-1, printing each fruit.
Key points
- Arrays store multiple values of the same type.
- Array indexes start at 0.
- Arrays have a fixed size once created.
- The Length property gives the total number of elements.
