Considering this class:
public class Foo
{
public Int32 MyField;
}
I guess the “MyField” member is not on the thread stack because as it could be accessed by several threads, it has to be definitely in the managed heap, but does it means it is boxed and unboxed everytime it is used?
Thanks in advance
No, it is not boxed every time it is used. Boxing only occurs when you are coercing a value type into a reference type – it really has nothing to do with where the actual memory for the value was allocated (or even if any memory was allocated).
In your case, it’s how you act on MyField that will determine if it’s boxed, not how Foo is treated.
Note that in the second example
valnow contains a reference to a boxed int.MyFieldis still (and will always remain) an unboxed int and can be accessed without unboxing (thanks for pointing out the needed clarification, LukeH)