Jan 082013
 January 8, 2013  Posted by at 12:47 pm Not So Stupid Questions  Add comments

[To celebrate my first year of programming I will ask a ‘stupid’ questions daily on my blog for a year, to make sure I learn at least 365 new things during my second year as a developer]

Pinning down an address so we know where to go

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.

  One Response to “Stupid Question 122: What is meant by pinning objects in C#?”

  1. Hi,

    99.99% of the time you want to pin an object, you are doing P/Invoke or other bridging/marshalling out in the unmanaged memory space.

    (Tip: do a “Stupid question” on P/Invoke – and check out http://www.pinvoke.net)


 Leave a Reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>



What is 5 + 15 ?
Please leave these two fields as-is:
IMPORTANT! To be able to proceed, you need to solve the following simple math (so we know that you are a human) :-)