C#: Using pointer types as fields?

Is it ever safe to use this construction? I mean for long term storage on the heap.

Yes. Doing so is usually foolish, painful and unnecessary, but it is possible.

From what I understand, the GC is free to move things around, and while it updates the references to something that's been moved, does it update pointers too?

No. That's why we make you mark it as unsafe.

I'm guessing no, which would make this construction very unsafe, right?

Correct.

I'm sure there are way superior alternatives to doing this, but call it morbid curiosity.

There certainly are.

is the pointer guaranteed to keep pointing to whatever you originally pointed it to?

Not unless you ensure that happens. There are two ways to do that.

Way one: Tell the garbage collector to not move the memory. There are two ways to do that:

  • Fix a variable in place with the "fixed" statement.

  • Use interop services to create a gc handle to the structures you wish to keep alive and in one place.

Doing either of these things will with high likelihood wreck the performance of the garbage collector.

Way two: Don't take references to memory that the garbage collector can possibly move. There are two ways to do that:

  • Only take addresses of local variables, value parameters, or stack-allocated blocks. Of course, in doing so you are then required to ensure that the pointers do not survive longer than the relevant stack frame, otherwise, you're referencing garbage.

  • Allocate a block out of the unmanaged heap and then use pointers inside that block. In essence, implement your own memory manager. You are required to correctly implement your new custom memory manager. Be careful.


Some obvious integrity checks have been excluded. The obvious problem with this is you have to allocate more than you will need because you cannot reallocate the buffer as the keyword fixed implies.

public unsafe class NodeList
{
    fixed Node _Nodes[1024];
    Node* _Current;

    public NodeList(params String[] data)
    {
        for (int i = 0; i < data.Length; i++)
        {
            _Nodes[i].Data = data[i];
            _Nodes[i].Next = (i < data.Length ? &_Nodes[i + 1] : null);     
        }

        _Current = &_Nodes[0];
    }

    public Node* Current()
    {
        return _Current++;  
    }
}

public unsafe struct Node
{
    public String Data;
    public Node* Next;
}