Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is a static value type field boxed in the heap in C#?

Tags:

c#

.net

Just out of curiosity - consider the following example:

public class A
{
    public static int Foo;
}

public class Program
{
    static void Main()
    {
        // The following variable will be allocated on the
        // stack and will directly hold 42 because it is a
        // value type.
        int foo = 42;

        // The following field resides on the (high frequency)
        // heap, but is it boxed because of being a value type?
        A.Foo = 42;
    }
}

My question is the following: is the value of the Foo field boxed because it resides on the heap? Or is it in a special container object / memory section that encapsulates it just like an instance value type field is part of an object on the heap?

I would assume that it is not boxed but I don't know for sure and I cannot find any documentation on it.

Thank you for your help.

like image 920
feO2x Avatar asked Sep 09 '14 10:09

feO2x


1 Answers

The CLR does not have the restriction that every field of a class needs to have the same storage type. Only instance members end up on the GC heap. Static members are allocated in the loader heap. Or in thread-local storage when the field has the [ThreadStatic] attribute. This of course enforces the contract that a static member is shared by every instance of an object of the class.

Very simply implemented btw, the jitter allocates the storage and knows the address of the field. So any load and stores directly use the address of the variable. There's no extra pointer dereference, very efficient.

So, no, there's no need at all to box, a static int will only occupy 4 bytes.

If you want to see this for yourself then use the Debug + Windows + Disassembly window. Shows the machine code, you'll see it using the address of the variable directly. It will be a different address every time you run the program, a malware counter-measure.

like image 74
Hans Passant Avatar answered Oct 01 '22 05:10

Hans Passant