C# Arrays - Complete Guide
Introduction to Arrays
Arrays in C# are fixed-size, indexable collections of elements of the same type. They are reference types that derive from System.Array and provide efficient, contiguous storage with O(1) indexed access.
Arrays are zero-indexed (the first element is at index 0). They are useful when the collection size is known up front and when you need fast random access to elements.
Array Declaration and Initialization
Arrays can be declared and initialized in several ways in C#:
Example
using System;
namespace ArrayDeclarationExample
{
class Program
{
static void Main(string[] args)
{
// Method 1: Declaration then initialization
int[] numbers1;
numbers1 = new int[5]; // Array of 5 integers (default values: 0)
// Method 2: Declaration with initialization size
int[] numbers2 = new int[5];
// Method 3: Declaration with explicit values
int[] numbers3 = new int[] { 1, 2, 3, 4, 5 };
// Method 4: Implicit-size initializer (common)
int[] numbers4 = { 1, 2, 3, 4, 5 };
// Method 5: Using var with explicit new[]
var numbers5 = new int[] { 1, 2, 3, 4, 5 };
// Different element types
string[] names = { "Alice", "Bob", "Charlie" };
double[] prices = { 9.99, 19.99, 29.99 };
bool[] flags = { true, false, true };
// Display array information
Console.WriteLine($"numbers1 length: {numbers1.Length}");
Console.WriteLine($"numbers4 length: {numbers4.Length}");
Console.WriteLine($"names length: {names.Length}");
// Accessing array elements
Console.WriteLine($"\nFirst element of numbers4: {numbers4[0]}");
Console.WriteLine($"Second element of names: {names[1]}");
Console.WriteLine($"Last element of prices: {prices[prices.Length - 1]}");
// Modifying array elements
numbers4[0] = 10;
names[1] = "Robert";
Console.WriteLine($"\nModified numbers4[0]: {numbers4[0]}");
Console.WriteLine($"Modified names[1]: {names[1]}");
// Default values
Console.WriteLine($"\nDefault values in numbers1:");
for (int i = 0; i < numbers1.Length; i++)
{
Console.WriteLine($"numbers1[{i}] = {numbers1[i]}");
}
}
}
}