when - managed heap c#

Can C# GC move memory objects (3)

Let's suppose this very basic C# code:

var tab = new int[10];

I have read that non fixed variables can be moved in memory by garbage collector.

My question is: Is it possible that "tab" address change during my program execution ?

I just want to understand.

In fact, no matter if tab value change.

Considering you are using var it means you are defining it in a method. Your variable lives in the context of that method for a very short time, and it is very unlikely that GC will move it.

On the other hand GC will move memory blocks to reduce memory fragmentation so yes it may move your variables. Best part of it you will not even notice it since it is same old "tab" for you.

If you want to be sure to fix location of that variable you can use "fixed".

It is certain that the array object could be moved in memory.

But note that you cannot obtain the pointer of a managed reference object, or you use a fixed block, it cannot be moved by GC within it.

If the array object is moved, the reference from variable tab to the array object is also fixed by GC, so there would be no way for you to see anything impacted by GC.

Yes. The memory address of tab can be (and most probably will be) changed. Reference: ECMA-334 C# Language Specification , chapter 23.4 .

The point is, in c# you don't need to bother about memory addresses as it's a managed language. All references to tab variable will be changed accordingly, and your program will survive garbage collection seamlessly.