Arrays
Fixed Arrays
Fixed arrays use the T[] syntax and are allocated with new T[size]:
int[] primes = new int[5];primes[0] = 2;primes[1] = 3;Console.WriteLine($"{primes.length}"); // 5
Vec2[] points = new Vec2[10]; // array of Vec2 valuesFixed arrays use .length (lowercase). They are GC-allocated and their length is set at creation time.
Dynamic Arrays
Dynamic arrays use the T[*] syntax and grow at runtime:
int[*] nums = int[*] { 1, 2, 3 };nums.Push(4);nums.Push(5);Console.WriteLine($"{nums.Length}"); // 5
int[*] range = int[*] { 1..10 }; // range initializer (1 through 10)Dynamic Array Methods
All dynamic array methods use PascalCase:
| Method | Description |
|---|---|
.Push(item) | Append item to end |
.Pop() | Remove and return last item |
.Insert(i, item) | Insert at index |
.RemoveAt(i) | Remove element at index |
.Remove(item) | Remove first occurrence |
.Clear() | Remove all elements |
.Contains(item) | Test membership |
.IndexOf(item) | Find first index (-1 if absent) |
.Reverse() | Reverse in place |
.Slice(start, end) | Return a sub-array |
.Concat(other) | Return a new array from self + other |
.ToArray() | Convert to a fixed T[] array |
.Length | Number of elements |
.Capacity | Current allocated capacity |
int[*] list = int[*] {};list.Push(3);list.Push(1);list.Push(2);list.Reverse();// list is now [2, 1, 3]Iterating Arrays
int[] scores = new int[3];scores[0] = 85;scores[1] = 92;scores[2] = 78;
for (int i = 0; i < scores.length; i++){ Console.WriteLine($"{scores[i]}");}Allocation: Plain vs GC
Dynamic arrays have two allocation paths:
| Syntax | Allocator | Cleanup | Use Case |
|---|---|---|---|
T[*] | malloc | Automatic on function return | Local value type |
new T[*] | GC heap | Garbage collected | Heap-shared reference |
Plain T[*] is automatically freed when the enclosing function returns. It cannot escape the function (cannot be returned or stored in a field). For those cases, use new T[*]:
int[*] local = int[*] { 1, 2, 3 }; // malloc'd, freed on return
int[*]? shared = new int[*] { 4, 5 }; // GC-allocated, can escapeMove and Copy
Dynamic arrays support move and copy for ownership control:
int[*] a = int[*] { 1, 2, 3 };int[*] b = move a; // a becomes empty, b owns the dataint[*] c = copy b; // c is an independent cloneAfter a move, the source is still a valid empty array. A copy allocates a new array and copies all elements.