CHAPTER 11 ADVANCED C# LANGUAGE FEATURES
unsafe { UnsafeSwap(&i, &j); }
}
Console.WriteLine("Values after unsafe swap: i = {0}, j = {1}", i, j);
Console.ReadLine();
Field Access via Pointers (the -> Operator)
Now assume you have defined a simple, safe Point structure, as follows:
struct Point
{
public int x;
public int y;
}
public override string ToString()
{
return string.Format("({0}, {1})", x, y);
}
If you declare a pointer to a Point type, you will need to make use of the pointer field-access
operator (represented by ->) to access its public members. As shown in Table 11-2, this is the unsafe
version of the standard (safe) dot operator (.). In fact, using the pointer indirection operator (*), it is
possible to dereference a pointer to (once again) apply the dot operator notation. Check out the unsafe
method:
unsafe static void UsePointerToPoint()
{
// Access members via pointer.
Point point;
Point* p = &point;
p->x = 100;
p->y = 200;
Console.WriteLine(p->ToString());
}
// Access members via pointer indirection.
Point point2;
Point* p2 = &point2;
(*p2).x = 100;
(*p2).y = 200;
Console.WriteLine((*p2).ToString());
The stackalloc Keyword
In an unsafe context, you may need to declare a local variable that allocates memory directly from the
call stack (and is, therefore, not subject to .NET garbage collection). To do so, C# provides the stackalloc
keyword, which is the C# equivalent to the _alloca function of the C runtime library. Here is a simple
example:
435