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;
}
}
}
}
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With