C# Language Pointers


Pointers and unsafe

Due to their nature, pointers produce unverifiable code. Thus, usage of any pointer type requires an unsafe context.

The type System.IntPtr is a safe wrapper around a void*. It is intended as a more convenient alternative to void* when an unsafe context isn't otherwise required to perform the task at hand.

Undefined behavior

Like in C and C++, incorrect usage of pointers can invoke undefined behavior, with possible side-effects being memory corruption and execution of unintended code. Due to the unverifiable nature of most pointer operations, correct usage of pointers is entirely a responsibility of the programmer.

Types that support pointers

Unlike C and C++, not all C# types have corresponding pointer types. A type T may have a corresponding pointer type if both of the following criteria apply:

  • T is a struct type or a pointer type.
  • T contains only members that satisfy both of these criteria recursively.