Skip to content

Pointers

Mario Gutierrez edited this page Jan 7, 2017 · 1 revision

Though rarely used in C# development, you can actually use pointers.

To use you need to:

  • Define the /unsafe flag on compilation: csc /unsafe *.cs
  • Enable the 'Allow unsafe code' option in Visual Studio.
  • Use the unsafe keyword for blocks and methods.

'unsafe'

class Program
{
  static void Main(string[] args)
  {
    unsafe
    {
      int myInt = 5;
      Square(&myInt);
    }
  }

  unsafe static void Square(int *n)
  {
    return *n *= *n;
  }
}
unsafe struct Node { /* ... */ }
struct Node
{
  public int Value;
  public unsafe Node* next; // Unsafe field.
}

Unlike in C and C++, the * operator must be next to the type for pointer declaration, e.g.,

public unsafe Node* left, right; // C#

instead of,

public Node *left, *right; // C, C++

'stackalloc'

char* p = stackalloc char[256]; // Declare memory on the stack.

'fixed'

To prevent a ReferenceType from being swept or moved by the GC while you are using its address, use the fixed keyword.

fixed (MyRefType* p = &refVar)
{
  Console.Write(p->ToString());
}

'sizeof'

Console.Write(sizeof(int));

// Must be in an 'unsafe' block for custom types.
unsafe { Console.Write(sizeof(Point)); }
Clone this wiki locally