Search code examples
c#structreturn-valueboxingvalue-type

Is a C# struct ever boxed when declared as the return value of a function?


A simple question, but I haven't found a definitive answer on Stack Overflow.

    struct MyStruct { int x, y, z; }

    MyStruct GetMyStruct() => new MyStruct();

    static void Main()
    {
        var x = GetMyStruct();      // can boxing/unboxing ever occur?
    }

Is a C# struct (value type) always copied to the stack when returned from a function, no matter how large it might be? The reason I'm unsure is that for some instruction sets other than MSIL (such as x86), a return value usually needs to fit into a processor register, and the stack is not directly involved.

If so, is it the call site that pre-allocates space on the CLR stack for the (expected) value return type?


[edit: Summary of replies]
For the intent of the original question, the answer is no; the CLR will never (silently) box a struct just for the purpose of transferring it as a return value.


Solution

  • 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.