Summary - Unsafe code
Combine unsafe, fixed and Span<T> to write a fast buffer copy.
Summary - Unsafe code
In this group you learned unsafe blocks, pointers (int*), pinning with fixed, stack allocation with stackalloc and Span<T>.
These tools are used where performance matters; in everyday code Span often replaces unsafe. Let's now write a small buffer copy and pinning example.
Exercise Copy a buffer with Span
Allocate 3 ints with Span<int> src = stackalloc int[3];. Assign src[0] = 1; src[1] = 2; src[2] = 3;. Allocate the target with Span<int> dst = stackalloc int[3];. Copy with src.CopyTo(dst); and print the last element with Console.WriteLine(dst[2]);.
Show example solution
Span<int> src = stackalloc int[3]; src[0] = 1; src[1] = 2; src[2] = 3; Span<int> dst = stackalloc int[3]; src.CopyTo(dst); Console.WriteLine(dst[2]);
Example solution:
using System;
class Program
{
static void Main()
{
Span<int> src = stackalloc int[3];
src[0] = 1; src[1] = 2; src[2] = 3;
Span<int> dst = stackalloc int[3];
src.CopyTo(dst);
Console.WriteLine(dst[2]);
}
}
unsafe and Span together
When unsafe is still needed, you can take a pointer from a Span with fixed: fixed (int* p = &span[0]). So Span is the safe side and unsafe the flexible side.
The right design is: try Span first, fall back to unsafe when needed. This solves most high-performance scenarios safely and reduces the risk of errors.
Exercise Print the second element with fixed
Make Main unsafe. Declare int[] arr = { 7, 14 };. Inside a fixed (int* p = &arr[0]) block, print the second element with Console.WriteLine(*(p + 1));.
Show example solution
unsafe static void Main() { int[] arr = {7,14}; fixed (int* p = &arr[0]) { Console.WriteLine(*(p + 1)); } }
Example solution:
using System;
class Program
{
unsafe static void Main()
{
int[] arr = { 7, 14 };
fixed (int* p = &arr[0])
{
Console.WriteLine(*(p + 1));
}
}
}
Test yourself
-
Which provides stack allocation without unsafe?
- new int[4]
- stackalloc int[4] (with Span)
- GC.Allocate
- fixed int[4]
Show answer
stackalloc int[4] (with Span) — Correct. stackalloc assigned to Span needs no unsafe.
-
Match the concepts
- unsafe
- Pointer permission
- int*
- Pointer to int
- fixed
- Pinning
- Span<T>
- Safe view