Raw Pointers
Pointer Types
| Syntax | Description | Nullable |
|---|---|---|
T* | Nullable raw pointer | Yes |
T& | Non-null raw pointer | No |
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 bodyAutomatic 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 orunsafefunction qualifier T*defaults tonullon declarationT&must be initialized and cannot hold null- Assigning
T*toT&performs a runtime null check