Glossary / Pointers
Pointers
A pointer is an unsafe value containing a memory address for a value of a specified type. C# pointers support direct memory access and arithmetic for interop or low-level algorithms, but bypass many runtime safety protections and require precise control of allocation, alignment, bounds, and lifetime.
Declaration and use
unsafe
{
int value = 10;
int* pointer = &value;
*pointer = 20;
}
Pointer types can point to unmanaged types and are used within unsafe contexts; managed references cannot be treated as stable raw pointers without pinning. fixed prevents the GC from moving the referenced object for the fixed scope. Native pointers from allocation APIs need matching free operations; do not mix allocator families. Pointer arithmetic is scaled by pointed-to type size and can leave valid memory without a managed bounds exception.
A pointer is not the same as IntPtr/nint, which represent native-sized integer/address values and are commonly used for interop handles. Neither type conveys ownership automatically. Prefer SafeHandle for operating-system handles.
Engineering guidance
Keep pointer code minimal, isolate it behind safe APIs, and specify pointer validity duration. Validate lengths before pointer operations and ensure pinning/cleanup occurs on all paths. Use spans for bounded managed buffers and test native layout/packing explicitly.
Interview questions
- How dereference a pointer? With
*pointerin an unsafe context. - Why use fixed? To pin managed storage while obtaining a stable address.
- Is IntPtr a pointer type? It is a native-sized integer wrapper, not a typed C# pointer.
- Are pointer bounds checked? Generally not; invalid accesses can corrupt memory or crash.
- What owns native memory? Explicit allocator/API contract; pair allocation with the correct release operation.