O'Reilly logo

C# Language Pocket Reference by Ted Neward, Ben Albahari, Peter Drayton

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Unsafe Code and Pointers

C# supports direct memory manipulation via pointers within blocks of code marked unsafe and compiled with the /unsafe compiler option. Pointer types are primarily useful for interop with C APIs, but may also be used for accessing memory outside the managed heap or for performance-critical hotspots.

Pointer Basics

For every value type or pointer type V, there is a corresponding pointer type V*. A pointer instance holds the address of a value. This is considered to be of type V, but pointer types can be (unsafely) cast to any other pointer type. Table 1-4 lists the main pointer operators.

Table 1-4. Principal pointer operators

Operator

Meaning

&

The address-of operator returns a pointer to the address of a value

*

The dereference operator returns the value at the address of a pointer

->

The pointer-to-member operator is a syntactic shortcut, in which x->y is equivalent to (*x).y

Unsafe Code

By marking a type, type member, or statement block with the unsafe keyword, you're permitted to use pointer types and perform C++-style pointer operations on memory within that scope. Here is an example of using pointers with a managed object:

unsafe void RedFilter(int[,] bitmap) {
  int length = bitmap.Length;
  fixed (int* b = bitmap) {
    int* p = b;
    for(int i = 0; i < length; i++)
      *p++ &= 0xFF;
  }
}

Unsafe code typically runs faster than a corresponding safe implementation, which in this case requires a nested loop with array indexing and bounds checking. ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required