0

This is my code. I have a try and finally statement. Within the try block i have a fixed statement which sets a pointer variable.

try
{
    fixed (char* chRef = p)
    {
        //code
    }
}
finally
{
    chRef = null;
}

Im struggling for a way to set the fixed pointer variable to null no matter how the try exits beause of scope. Please help.

char* chRef;
try
{
    fixed (chRef = p)
    {
        //code
    }
}
finally
{
    chRef = null;
}

Gives me "Error 12 The type of a local declared in a fixed statement must be a pointer type"

ollo
  • 24,797
  • 14
  • 106
  • 155
user2390368
  • 101
  • 2
  • 9
  • AFAIK, you must *declare* (you don't have to initialize it) the `chRef` var on a broader scope. That is, before the `try`. – Andre Calil May 21 '13 at 13:10
  • 1
    wow a pointer in c#. That's interesting. :-) – Nicholas King May 21 '13 at 13:12
  • @AndreCalil thanks tried that. Gives me an identifier expected error on the assignment. – user2390368 May 21 '13 at 13:13
  • What do you intend to do with that chRef pointing to NULL? – JeffRSon May 21 '13 at 13:18
  • 2
    There is no point at all in setting it to null. The variable is out of scope past the end of the fixed statement. You couldn't abuse it if you want to. Don't fix this problem. – Hans Passant May 21 '13 at 13:22
  • Purpose of fixing chRef is to prevent Garbage Collector from moving p around the heap - this is called pinning. There is no point to set chRef to null because it has no purpose outside the fixed statement. Variable p is no longer protected from being moved after the fixed statement and it has nothing to do with chRef any more. – Zoran Horvat May 21 '13 at 13:41

1 Answers1

0

Were this to even be possible, you'd need to ensure that chRef was in scope. And that would mean putting it inside the fixed statement. So you'd write this:

fixed (char* chRef = p)
{
    try
    {
        //code
    }
    finally
    {
        chRef = null;
    }
}

But that does not work because you are not allowed to assign to the pointer chRef. It is, after all, fixed! If you attempt to assign to a fixed pointer the compiler objects:

error CS1656: Cannot assign to 'chRef' because it is a 'fixed variable'

Even if you could do this, which you cannot, there would be no point. Since chRef is about to leave scope, it would make no sense to modify it when you know that nothing could ever observe that modification.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490