Skip to content

Raw Pointers

Pointer Types

SyntaxDescriptionNullable
T*Nullable raw pointerYes
T&Non-null raw pointerNo

Basic Usage

All pointer operations require an unsafe block:

unsafe
{
int* p = new* int(); // heap allocate (nullable)
*p = 42; // dereference write
int val = *p; // dereference read
Point* pt = new* Point(10, 20);
int x = pt->x; // arrow operator for fields
pt->y = 30;
delete* p; // manual deallocation
delete* pt;
}

Non-Null Pointers (T&)

T& guarantees the pointer is never null:

unsafe
{
int x = 42;
int& p = &x; // non-null pointer to x
*p = 100; // OK: p is guaranteed non-null
// int& q = null; // ERROR: cannot assign null to T&
int* nullable = null;
// int& safe = nullable; // runtime null check
}

Unsafe Functions

Functions that use pointers can be marked unsafe with a trailing qualifier:

int DerefPointer(int* p) unsafe { return *p; }
int DerefExpr(int* p) unsafe *p; // expression body

Automatic Conversions

Pointers convert automatically to ref parameters:

void Increment(ref int val) { val = val + 1; }
unsafe
{
int* p = new* int();
*p = 10;
Increment(*p); // pass dereferenced pointer as ref
// *p is now 11
delete* p;
}

Safety Rules

  • All pointer operations require unsafe { } blocks or unsafe function qualifier
  • T* defaults to null on declaration
  • T& must be initialized and cannot hold null
  • Assigning T* to T& performs a runtime null check