C# Arrays
An array in C# stores multiple values of the same type under one variable name. Arrays matter because they give you fast indexed access to a fixed-size group of data, such as scores, names, prices, grid cells, or lookup values.
Unlike a single variable, an array has positions called indexes. The first item is at index 0, the second at index 1, and so on.
Overview: How C# Arrays Work
A C# array is an object managed by the Common Language Runtime. When you create an array with new, the CLR allocates one object that contains the array length and enough storage for all elements. The array length is fixed after creation, but the values stored in the elements can usually be changed.
Arrays are strongly typed. An int[] can store only int values, a string[] can store only string references, and a bool[] can store only Boolean values. This lets the compiler catch many mistakes before your program runs.
For value types such as int, double, and bool, the array stores the values directly in its element storage. For reference types such as string or custom classes, the array stores references. The referenced objects live elsewhere on the managed heap. That distinction matters when you copy arrays: assigning one array variable to another copies the reference to the same array object, not all the elements.
Every array has a Length property. Valid indexes are from 0 through Length - 1. If you try to read or write outside that range, the runtime throws an IndexOutOfRangeException. Bounds checking is one reason arrays are safer than raw memory access in lower-level languages.
Arrays are ideal when the number of elements is known or naturally fixed: seven days, twelve months, a row of test answers, or a game board. If the collection needs to grow and shrink frequently, List<T> is usually easier because it manages resizing for you.
Syntax
type[] name = new type[length];
type[] name = { value1, value2, value3 };
type[,] grid = new type[rows, columns];
type[][] jagged = new type[rowCount][];
| Part | Meaning |
|---|---|
type[] |
A one-dimensional array whose elements all have the specified type. |
new type[length] |
Creates an array object with a fixed number of elements. |
{ ... } |
An initializer that creates the array and fills it with listed values. |
type[,] |
A rectangular two-dimensional array where every row has the same number of columns. |
type[][] |
A jagged array, which is an array of arrays. Rows can have different lengths. |
New arrays are filled with the default value for their element type. Numeric elements start at 0, bool elements start at false, and reference type elements start at null.
Examples
Creating and Reading an Array
using System;
class Program
{
static void Main()
{
string[] names = { "Ada", "Grace", "Linus" };
Console.WriteLine(names[0]);
Console.WriteLine(names[2]);
Console.WriteLine($"Count: {names.Length}");
}
}
Output:
Ada
Linus
Count: 3
The array contains three strings, so its valid indexes are 0, 1, and 2. Reading names[0] returns the first element, not the zeroth in ordinary language. The Length property tells you how many elements exist, not the last index.
Updating Values and Looping
using System;
class Program
{
static void Main()
{
int[] scores = new int[4];
scores[0] = 84;
scores[1] = 91;
scores[2] = 76;
scores[3] = 100;
int total = 0;
for (int i = 0; i < scores.Length; i++)
{
total += scores[i];
}
double average = (double)total / scores.Length;
Console.WriteLine($"Total: {total}");
Console.WriteLine($"Average: {average:F2}");
}
}
Output:
Total: 351
Average: 87.75
This example creates an array with four slots, then fills each slot. A for loop is useful when you need the index. The condition i < scores.Length is the standard safe pattern because the loop stops before i becomes an invalid index.
Using Array Methods
using System;
class Program
{
static void Main()
{
int[] numbers = { 8, 3, 10, 1, 3 };
Array.Sort(numbers);
Console.WriteLine(string.Join(", ", numbers));
int index = Array.IndexOf(numbers, 10);
Console.WriteLine($"10 is at index {index}");
int[] lastThree = numbers[2..];
Console.WriteLine(string.Join(" | ", lastThree));
}
}
Output:
1, 3, 3, 8, 10
10 is at index 4
3 | 8 | 10
The Array class provides useful static methods. Array.Sort changes the existing array in place. Array.IndexOf returns the first matching index, or -1 if the value is not found. The range expression numbers[2..] creates a new array containing elements from index 2 through the end.
Rectangular and Jagged Arrays
using System;
class Program
{
static void Main()
{
int[,] board =
{
{ 1, 2, 3 },
{ 4, 5, 6 }
};
Console.WriteLine($"Center-right value: {board[1, 1]}");
string[][] teams = new string[2][];
teams[0] = new[] { "Mia", "Noah" };
teams[1] = new[] { "Ivy", "Omar", "Raj" };
Console.WriteLine($"Second team size: {teams[1].Length}");
}
}
Output:
Center-right value: 5
Second team size: 3
A rectangular array uses one object with two dimensions, so every row has the same number of columns. A jagged array is an array whose elements are themselves arrays, so each row can have a different length. Notice the indexing difference: rectangular arrays use board[row, column], while jagged arrays use teams[row][column].
How It Works Step by Step
- The compiler sees a declaration such as
int[] scoresand treatsscoresas a variable that can refer to an array of integers. - The expression
new int[4]asks the CLR to allocate a managed array object with four integer elements. - The CLR initializes each element to its default value. For
int, that is0. - When your code uses
scores[2], the runtime verifies that index2is inside the array bounds. - If the index is valid, the element is read or written. If not, an exception is thrown immediately.
- When no live references point to the array anymore, the garbage collector can reclaim its memory.
Because arrays are reference types, this code does not duplicate the elements: int[] b = a;. Both variables now refer to the same array. To make a separate copy, use Array.Copy, Clone with a cast, or LINQ’s ToArray when appropriate.
Common Mistakes
Using Length as the Last Index
int[] values = { 10, 20, 30 };
Console.WriteLine(values[values.Length]);
This is wrong because values.Length is 3, but the last valid index is 2. Correct code subtracts one when you want the final element.
using System;
class Program
{
static void Main()
{
int[] values = { 10, 20, 30 };
Console.WriteLine(values[values.Length - 1]);
}
}
Output:
30
Expecting Assignment to Copy an Array
using System;
class Program
{
static void Main()
{
int[] original = { 1, 2, 3 };
int[] alias = original;
alias[0] = 99;
Console.WriteLine(original[0]);
}
}
Output:
99
This compiles, but it often surprises beginners. alias and original point to the same array. If you need a different array, copy the elements into a new array.
using System;
class Program
{
static void Main()
{
int[] original = { 1, 2, 3 };
int[] copy = new int[original.Length];
Array.Copy(original, copy, original.Length);
copy[0] = 99;
Console.WriteLine(original[0]);
Console.WriteLine(copy[0]);
}
}
Output:
1
99
Putting the Wrong Type in an Array
int[] counts = { 1, 2, 3 };
counts[0] = "one";
This does not compile because an int[] can hold only integers. Choose the correct element type before creating the array.
Best Practices
- Use arrays when the size is fixed or known in advance.
- Use
List<T>when you frequently add or remove items. - Loop with
i < array.Length, noti <= array.Length. - Prefer
foreachwhen you only need values and do not need indexes. - Use clear plural names such as
scores,names, ortemperatures. - Remember that assigning an array variable copies the reference, not the array contents.
- Be careful with nullable reference type arrays, because new elements can start as
null. - For grid-like data, choose rectangular arrays when every row has equal length and jagged arrays when row lengths vary.
Practice Exercises
- Create an
int[]with five prices, then print the highest price. Hint: start with the first element as the current maximum. - Create a
string[]of names and print each name with its index, such as0: Ada. - Create a jagged array for three classrooms where each classroom can have a different number of students. Print the size of each classroom.
Summary
- An array stores a fixed number of elements of one type.
- Array indexes start at
0, so the last valid index isLength - 1. - Arrays are reference types managed by the CLR.
Array.Sort,Array.IndexOf, ranges, loops, andforeachare common array tools.- Rectangular arrays use comma-separated indexes; jagged arrays are arrays of arrays.
- Use arrays for fixed-size data and collections such as
List<T>for changing sizes.
