iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

Arrays

C# arrays are zero-indexed, fixed-length, and reference types. The modern toolkit: List<T> for growth, LINQ for transforms, Span<T> / Memory<T> for zero-allocation slicing.

Arrays + Span + LINQ

EXAMPLE
using System;
using System.Linq;

// 1) Declaration
int[]    a = new int[5];               // {0,0,0,0,0}
int[]    b = { 1, 2, 3, 4, 5 };
string[] c = new string[]{ "a", "b" };
int[,]   grid = { { 1, 2 }, { 3, 4 } }; // 2-D multidimensional
int[][]  jag  = { new[]{ 1, 2 }, new[]{ 3, 4, 5 } }; // jagged

// 2) Length
Console.WriteLine(b.Length);
Console.WriteLine(grid.GetLength(0)); // rows
Console.WriteLine(grid.GetLength(1)); // cols

// 3) Iterate
foreach (var n in b) Console.WriteLine(n);
for (var i = 0; i < b.Length; i++) Console.WriteLine(b[i]);

// 4) Array utility
Array.Sort(b);
Array.Reverse(b);
Array.Fill(a, 1);
var idx = Array.BinarySearch(b, 3);
var copy = (int[])b.Clone();

// 5) LINQ — same toolkit as List<T>
var sum   = b.Sum();
var max   = b.Max();
var evens = b.Where(x => x % 2 == 0).ToArray();
var sums  = b.Select(x => x * 2).ToList();
var dict  = users.ToDictionary(u => u.Id);

// 6) Range / Index — slicing without allocation when using Span
var middle = b[1..^1];                  // [2, 3, 4]  — copies
ReadOnlySpan<int> span = b.AsSpan(1..^1); // view, zero allocation

foreach (var x in span) Console.WriteLine(x);

// 7) Span<T> + stackalloc — hot-path patterns
Span<int> tmp = stackalloc int[16];
for (var i = 0; i < tmp.Length; i++) tmp[i] = i * i;

// 8) Compare arrays — Array.Equals is reference; use SequenceEqual
int[] x = { 1, 2, 3 };
int[] y = { 1, 2, 3 };
Console.WriteLine(x == y);            // False — different refs
Console.WriteLine(x.SequenceEqual(y)); // True

// 9) Multi-dim helpers
for (var r = 0; r < grid.GetLength(0); r++) {
    for (var c = 0; c < grid.GetLength(1); c++) {
        Console.Write(grid[r, c] + " ");
    }
    Console.WriteLine();
}

// 10) Prefer List<T> for growth, Span<T> for slicing perf, Array.Empty<T>() over allocating
var empty = Array.Empty<int>();

Why it matters

Span<T> + stackalloc + slicing is the modern recipe for zero-allocation hot paths. For everything else, List<T> + LINQ is cleaner than arrays + loops.

Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.

Example

Example
int[] nums = {1, 2, 3, 4};
Console.WriteLine(nums[0]);
Console.WriteLine(nums.Length);
Try it Yourself »

Discussion

Loading…