Is a C# struct ever boxed when declared as the return value of a function?
It is a heavy implementation detail of the JIT compiler. In general, if the struct is small enough and has simple members then its gets returned in CPU registers. If it gets too big then the calling code reserves enough space on the stack and passes a pointer to that space as an extra hidden argument.
It will never be boxed, unless the return type of the method is object of course.
Fwiw: this is also the reason that the debugger cannot display the return value of the function in the Autos window. Painful sometimes. But the debugger doesn't get enough metadata from the JIT compiler to know exactly where to find the value. Edit: fixed in VS2013.
A struct is boxed whenever you want to treat it as an object
, so if you call Func
and assign the result to object it will be boxed.
E.g. doing this
object o = Func();
will yield the following IL
L_0000: call valuetype TestApp.foo TestApp.Program::Func()
L_0005: box TestApp.foo
L_000a: stloc.0
which shows that the return value is boxed, because we assign it to a reference of the type object
.
If you assign it to a variable of type Foo
it isn't boxed and thus it is copied and the value is stored on the stack.
Also, boxing wouldn't really help you here since it would involve creating an object to represent the value of the struct, and the values are effectively copied during the boxing operation.