Stupid Question 122: What is meant by pinning objects in C#?
Pinning down an address so we know where to go
Sounds fun? This has nothing to do with the popular site PinInterest- but we are pinning things (objects).
The problem with pointers are that as I explained in the pointer series (Stupid Question 118: The pointer series: What is a pointer?) a pointer points to an address in memory, a memory address. So we expect to find something, a particular thing, at that address. And the Garbage Collector likes to move stuff around (pointers in C# : Stupid Question 119: Do we have pointers in C#?) . Realocate objects. And it does so freely to make room, by gathering the items ,- more compact. Those good intentions cause problems for our pointer usage, and a way to solve this is by pinning the objects. By using the fixed keyword you tell the GarbageCollector not to move the object (only allowed in unsafe code:Stupid Question 121: What is meant by ‘unsafe code’ in .Net?). The object will keep its address so when we get the address for that party – we know it’s the right one.
Last modified on 2013-01-08