CHAPTER 11 ADVANCED C# LANGUAGE FEATURES
int myInt = 10;
// OK, because we are in an unsafe context.
SquareIntPointer(&myInt);
Console.WriteLine("myInt: {0}", myInt);
}
int myInt2 = 5;
}
// Compiler error! Must be in unsafe context!
SquareIntPointer(&myInt2);
Console.WriteLine("myInt: {0}", myInt2);
If you would rather not force the caller to wrap the invocation within an unsafe context, you could
update Main() with the unsafe keyword. In this case, the following code would compile:
unsafe static void Main(string[] args)
{
int myInt2 = 5;
SquareIntPointer(&myInt2);
Console.WriteLine("myInt: {0}", myInt2);
}
If you run this Main() method, you will see the following output:
myInt: 25
Working with the * and & Operators
After you have established an unsafe context, you are then free to build pointers to data types using the *
operator and obtain the address of what is being pointed to using the & operator. Unlike in C or C++, in
C# the * operator is applied to the underlying type only, not as a prefix to each pointer variable name.
For example, consider the following code, which illustrates both the correct and incorrect ways to
declare pointers to integer variables:
// No! This is incorrect under C#!
int *pi, *pj;
// Yes! This is the way of C#.
int* pi, pj;
Consider the following unsafe method:
unsafe static void PrintValueAndAddress()
{
int myInt;
// Define an int pointer, and
// assign it the address of myInt.
int* ptrToMyInt = &myInt;
433