views:

88

answers:

3

The following code works, but I can't figure out what's going on memory-wise. Where and how is the struct value t copied?

interface ITest { void Hello(); }    

struct STest : ITest
{
    public void Hello() { Console.WriteLine("Hello"); }
}

static ITest Make()
{
    STest t = new STest();
    return t;
}

static void Main(string[] args)
{
    ITest it = Make();
    it.Hello();
}
+6  A: 

When you cast the struct to an interface, it boxes the struct if that is what you are asking? http://blogs.msdn.com/abhinaba/archive/2005/10/05/477238.aspx

Kevin
+4  A: 

It will be boxed on the return t; statement. At this point, the value is copied from the stack to the heap.

Dave Cluderay
Or copied from the heap to the heap, if the struct was in a field of a heap-allocated type.
Joren
+3  A: 

When you return from Make(), and assign to "it", you're returning a copy of the "t" struct from the stack inside of Make().

This is then boxed into an object, and assigned to the interface "it". The interface, holds a reference to the "boxed" copy of the struct, which you then use to call Hello().

Reed Copsey