An array is a container that holds multiple values of the same type. Think of it like a row of lockers โ each locker has a number (index), and each holds one item.
Declaring and Initializing Arrays
Use square brackets to say "this is an array." You can set the size upfront or let C# count the elements for you.
using System;
class Program {
static void Main() {
int[] numbers = new int[5];
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
numbers[3] = 40;
numbers[4] = 50;
Console.WriteLine(numbers[2]);
}
}
Try it Yourself โ
Array Initializer Syntax
Shorter way: provide all values in curly braces and skip the size. C# figures out the length.
using System;
class Program {
static void Main() {
int[] numbers = { 10, 20, 30, 40, 50 };
Console.WriteLine(numbers[0]);
Console.WriteLine(numbers[numbers.Length - 1]);
}
}
Try it Yourself โ
Array Length
The Length property tells you how many elements are in the array. Remember: indices go from 0 to Length - 1.
using System;
class Program {
static void Main() {
string[] names = { "Alice", "Bob", "Charlie" };
Console.WriteLine("Array size: " + names.Length);
}
}
Try it Yourself โ
Looping Through Arrays
Use a for loop with the index, or a foreach loop to go through each element automatically.
using System;
class Program {
static void Main() {
int[] nums = { 2, 4, 6, 8, 10 };
for (int i = 0; i < nums.Length; i++) {
Console.WriteLine("Index " + i + ": " + nums[i]);
}
int sum = 0;
foreach (int n in nums) {
sum += n;
}
Console.WriteLine("Sum: " + sum);
}
}
Try it Yourself โ
Arrays Are Fixed Size
Once you set the size, it can't change. If you need a growable collection, look at List<T> instead.
using System;
class Program {
static void Main() {
int[] nums = { 1, 2, 3 };
Console.WriteLine("Fixed at " + nums.Length + " elements");
}
}
Try it Yourself โ