Unsafe Code, Pointers & Native Interop
Use unsafe pointers when direct memory access is truly required and call native Windows APIs through P/Invoke while keeping unsafe code tightly scoped.
Part 1: What You Will Learn
Use unsafe pointers when direct memory access is truly required and call native Windows APIs through P/Invoke while keeping unsafe code tightly scoped.
- Enable unsafe compilation for a project.
- Pin a managed array with `fixed` before taking a pointer to its data.
- Use pointer arithmetic to read contiguous values.
- Call a native DLL function with `DllImport`.
Project setup: Create a .NET 10 Console App. In the project properties or .csproj, enable unsafe code with `<AllowUnsafeBlocks>true</AllowUnsafeBlocks>`. The P/Invoke example is Windows-specific.
Part 2: Topic-Specific Working Example
The following example is written specifically for this lesson. Create the project described above, enter the code, run it, and then change some values to observe how the feature behaves.
using System.Runtime.InteropServices;
public static class NativeMethods
{
[DllImport("kernel32.dll")]
public static extern ulong GetTickCount64();
}
static unsafe int SumWithPointer(int[] values)
{
int total = 0;
fixed (int* pointer = values)
{
for (int i = 0; i < values.Length; i++)
{
total += *(pointer + i);
}
}
return total;
}
int[] numbers = [10, 20, 30, 40];
unsafe
{
Console.WriteLine($"Pointer sum: {SumWithPointer(numbers)}");
}
ulong milliseconds = NativeMethods.GetTickCount64();
Console.WriteLine($"Windows uptime: {milliseconds} ms");Part 3: How the Code Works
- `fixed` pins the managed array so the garbage collector cannot move it while a pointer refers to its memory.
- `*(pointer + i)` dereferences the pointer at the requested element offset.
- P/Invoke maps a managed method declaration to an exported function in a native library.
- Unsafe code bypasses important runtime protections, so use Span<T>, Memory<T>, or safe interop APIs whenever they can solve the problem.
Part 4: Mini Project & Practice
Mini project: write an unsafe method that finds the maximum value in an int array using a pointer. Then write the same method safely with Span<int> and compare readability.
Tip: Type the code yourself in Visual Studio 2026, run it, then deliberately change one part at a time. The goal is to understand the feature rather than simply copy the finished example.
When you are comfortable with this lesson, continue to Lesson 35.
C# in Visual Studio 2026
📘 This lesson is part of the book C# in Visual Studio 2026 by Dr. Liew Voon Kiong.
View on Amazon Kindle Edition