Is a static value type field boxed in the heap in C#?
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.
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.
As Sriram and Lee have given the answer in the comments of the question but did not provide an answer, I'll summarize the findings:
No, the value is not boxed. Value Types can reside on the heap, they are only boxed when they are used like a Reference Type.
You can also see that there is no boxing involved in the IL code of my example:
.method private hidebysig static void Main() cil managed
{
.entrypoint
// Code size 12 (0xc)
.maxstack 1
.locals init ([0] int32 foo)
IL_0000: nop
IL_0001: ldc.i4.s 42
IL_0003: stloc.0
IL_0004: ldc.i4.s 42
IL_0006: stsfld int32 StaticValueTypeFieldBoxing.A::Foo
IL_000b: ret
} // end of method Program::Main
链接地址: http://www.djcxy.com/p/78898.html
上一篇: 数组内存分配说明
下一篇: 在C#堆中是否装有静态值类型的字段?