Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't use keyword 'fixed' for a variable in C#

I tested the keyword fixed with array and string variables and worked really well but I can't use with a single variable.

static void Main() {

    int value = 12345;
    unsafe {
        fixed (int* pValue = &value) { // problem here
            *pValue = 54321;
        }
    }
}

The line fixed (int* pValue = &value) causes a complier error. I don't get it because the variable value is out of the unsafe block and it is not pinned yet.

Why can't I use fixed for the variable value?

like image 621
Jenix Avatar asked Dec 08 '22 01:12

Jenix


1 Answers

This is because value is a local variable, allocated on the stack, so it's already fixed. This is mentioned in the error message:

CS0213 You cannot use the fixed statement to take the address of an already fixed expression

If you need the address of value, you don't need the fixed statement, you can get it directly:

int* pValue = &value;
like image 170
Thomas Levesque Avatar answered Dec 10 '22 13:12

Thomas Levesque