Table 17-1 illustrates how the standard C/C++ pointer semantics are upheld in C#.
Table 17-1 C/C++ Pointer Operators-
Operator
|
Description
|
&
|
The address-of operator returns a pointer that represents the memory address of the variable.
|
*
|
The dereference operator is used to denote the value pointed at by the pointer.
|
->
|
The dereferencing and member access operator is used for member access and pointer dereferencing.
|
The following example will look familiar to any C or C++ developers. Here I'm calling a method that takes two pointers to variables for type int and modifies their values before returning to the caller. Not very exciting, but it does illustrate how to use pointers in C#.
// Compile this application with the /unsafe option. using System; class Unsafe1App { public static unsafe void GetValues(int* x, int* y) { *x = 6; *y = 42; } public static unsafe void Main() { int a = 1; int b = 2; Console.WriteLine("Before GetValues() : a = {0}, b = {1}", a, b); GetValues(&a, &b); Console.WriteLine("After GetValues() : a = {0}, b = {1}", a, b); } }
This sample needs to be compiled with the /unsafe compiler option. The output from this application should be the following: -
Before GetValues() : a = 1, b = 2 After GetValues() : a = 6, b = 42