C# Unsafe Code and Pointers
Unsafe code works with pointers, which hold the address of a value in memory. Dereferencing a pointer reads or writes the value stored at that address.
Reading through a pointer
The pointer holds the address of the level. Dereferencing it reads the stored value.
using System;
class Program
{
static void Main(string[] args)
{
unsafe
{
int level = 3;
int* p = &level;
Console.WriteLine(*p);
}
}
}Writing through a pointer
The assignment writes 9 through the pointer. The level variable itself now holds the new value.
using System;
class Program
{
static void Main(string[] args)
{
unsafe
{
int level = 4;
int* p = &level;
*p = 9;
Console.WriteLine(level);
}
}
}Pointer arithmetic over a buffer
The buffer holds three ints in a row. Adding 1 to the pointer reaches the second value, which prints.
using System;
class Program
{
static void Main(string[] args)
{
unsafe
{
int* p = stackalloc int[3];
*p = 5;
*(p + 1) = 7;
*(p + 2) = 9;
Console.WriteLine(*(p + 1));
}
}
}Example
using System;
class Program
{
static void Main(string[] args)
{
unsafe
{
int a = 3;
int b = 8;
int* pa = &a;
int* pb = &b;
int temp = *pa;
*pa = *pb;
*pb = temp;
Console.WriteLine(a);
Console.WriteLine(b);
}
}
}Key points
- Pointer code sits inside an unsafe block or an unsafe member.
- A pointer type is written with a star, such as int* for a pointer to an int.
- The & operator takes the address of a variable.
- The * operator dereferences a pointer, reaching the value at the address.
- Pointer arithmetic moves a pointer by whole elements of the pointed-to type.
- A project must enable unsafe code before pointers compile. Without that switch, the compiler reports error CS0227 and the build fails.
In this example, two pointers hold the addresses of a and b. The swap reads and writes only through the pointers, using a plain int as temporary storage. The prints show the values exchanged, 8 then 3.
Note
These examples never print an address, because address values can differ from run to run.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does `*p = 9;` do when p points at the variable level?