Wednesday, September 16, 2009

I almost forgot that C# supports pointers

As I was working on a new feature today, I noticed the following when creating a new string instance:

What's that strange '*' again? It's the syntax to use a pointer of course! I almost forgot that C# supported pointers. (Those d*mned managed languages!) .

If you can't remember what a pointer is, it's an address references to a memory position. In .NET the garbage collector (GC) manages the memory. This means that whenever the GC cleans up the memory, it can reallocate the data and as a consequence those address references can change. If you don't like it, the fixed keyword prevents this reallocation.

This sample shows you how to use pointers in your code:

using System;

class Test
{
      unsafe static void WriteLocations()
     {
            int *p;
            int i;


            i = 10;
            p = &i;


           string addr;
           addr = Convert.ToString((int)p);


           //Format pointer
           Console.WriteLine(addr);
           Console.WriteLine(*p);
          
           *p = 100;


            Console.WriteLine(i);


           //Change value through pointer
           i = *(&i) + 15;


          Console.WriteLine(i);
     }


     static void Main()
     {
          WriteLocations();
     }
}

Don't forget that using pointers in your code makes the assembly unsafe. So you'll have to use the /unsafe parameter to compile it. As a general rule avoid the direct use of pointers. There is a good reason why we have managed languages in the first place.

No comments: