Memory Management and Span<T>

Advanced Updated November 16, 2024

🧠 5. Memory Management: Span, stackalloc, and Unsafe Code

🔸 Span

Span provides fast memory-safe access to slices of arrays or buffers without allocations.

Span<int> numbers = stackalloc int[5];
for (int i = 0; i < numbers.Length; i++)
    numbers[i] = i * 2;

🔸 Unsafe Code

unsafe
{
    int x = 10;
    int* ptr = &x;
    Console.WriteLine(*ptr);
}
| Concept     | Use Case                              |
|-------------|---------------------------------------|
| `Span<T>`   | Fast, safe memory operations          |
| `stackalloc`| Allocates memory on stack             |
| `unsafe`    | For interop and high-perf computing   |