Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fixed Statement in C#

We have similar code to the following in one of our projects. Can anyone explain (in simple English) why the fixed statement is needed here?

class TestClass
{
    int iMyVariable;
    static void Main()
    {
        TestClass oTestClass = new TestClass();
        unsafe
        {
            fixed (int* p = &oTestClasst.iMyVariable)
            {
                *p = 9;
            }
        }
    }
}
like image 406
BrianG Avatar asked Sep 30 '08 14:09

BrianG


People also ask

What is fixed keyword in C?

The fixed keyword is used to prevent the garbage collector from relocating a variable. You may only use this in an unsafe context. fixed (int *c = &shape. color) { *c = Color.

What is fixed in programming?

2. Fixed refers to anything that is stationary and does not move or change. For example, with computer software, a fixed toolbar is a toolbar that stays in the same place, unlike a floating toolbar that moves around. 3.


2 Answers

It fixes the pointer in memory. Garbage collected languages have the freedom to move objects around memory for efficiency. This is all transparent to the programmer because they don't really use pointers in "normal" CLR code. However, when you do require pointers, then you need to fix it in memory if you want to work with them.

like image 71
ilitirit Avatar answered Oct 05 '22 17:10

ilitirit


The fixed statement will "pin" the variable in memory so that the garbage collector doesn't move it around when collecting. If it did move the variable, the pointer would become useless and when you used it you'd be trying to access or modify something that you didn't intend to.

like image 23
Blair Conrad Avatar answered Oct 05 '22 16:10

Blair Conrad