C Sharp

Using Pointers in C#

Let's look at some rules regarding the use of pointers and unsafe code in C#, and then we'll dive into some examples. Pointers can be acquired only for value types, arrays, and strings. Also note that in the case of arrays the first element must be a value type because C# is actually returning a pointer to the first element of the array and not the array itself. Therefore, from the compiler's perspective, it is still returning a pointer to a value type and not a reference type.

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