CHAPTER 11 ADVANCED C# LANGUAGE FEATURES
class Program
{
static void Main(string[] args)
{
unsafe
{
// Work with pointer types here!
}
}
// Can't work with pointers here!
}
In addition to declaring a scope of unsafe code within a method, you can build structures, classes,
type members, and parameters that are “unsafe.” Here are a few examples to gnaw on (no need to define
the Node or Node2 types in your current project):
// This entire structure is "unsafe" and can
// be used only in an unsafe context.
unsafe struct Node
{
public int Value;
public Node* Left;
public Node* Right;
}
// This struct is safe, but the Node2* members
// are not. Technically, you may access "Value" from
// outside an unsafe context, but not "Left" and "Right".
public struct Node2
{
public int Value;
// These can be accessed only in an unsafe context!
public unsafe Node2* Left;
public unsafe Node2* Right;
}
Methods (static or instance level) may be marked as unsafe as well. For example, assume you know
that a particular static method will make use of pointer logic. To ensure that this method can be called
only from an unsafe context, you could define the method as follows:
unsafe static void SquareIntPointer(int* myIntPointer)
{
// Square the value just for a test.
*myIntPointer *= *myIntPointer;
}
The configuration of our method demands that the caller invoke SquareIntPointer() as follows:
static void Main(string[] args)
{
unsafe
{
432