O'Reilly logo

C# Essentials by Peter Drayton, Ben Albahari, Brad Merrill

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. Pointer types are primarily useful for interoperability with C APIs but may also be used for accessing memory outside the managed heap or for performance-critical hotspots.

Pointer Types

For every value type or pointer type V in a C# program, there is a corresponding C# pointer type named V*. A pointer instance holds the address of a value. That value is considered to be of type V, but pointer types can be (unsafely) cast to any other pointer type. Table 2.3 summarizes the principal pointer operators supported by the C# language.

Table 2-3. 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, where

x->y is equivalent to (*x).y.

Unsafe Code

Methods, statement blocks, or single statements can be marked with the unsafe keyword to perform C++-style pointer operations on memory. Here is an example that uses pointers with a managed object:

unsafe void RedFilter(int[,] bitmap) {
  const 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 would have required a nested loop with array indexing and bounds checking. An unsafe ...

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