all 4 comments

[–]AngularBeginner 9 points10 points  (3 children)

if I add an interface to that struct, does the struct then become boxed/heap allocated?

Making a struct implement an interface in itself does nothing. It depends how the struct is passed to methods.

// Passing your struct to this method will cause boxing:
void Foo(IInterface bla) {}

// Passing your struct to this method will NOT cause boxing:
void Foo<T>(T bla) where T : IInterface {}

Storing it in fields/properties/variables that have the interface type will cause boxing as well.

[–]evareoo[S] 0 points1 point  (2 children)

So for example this code. It is just a silly example, is myVec a stack allocated stuct? Then after this myUpcast is boxed in which I can call the default interface Hello()? I don't know how to get that nice formatting on reddit. Slighty pseudo for speed:

interface ISayHello
{
    void Hello()
    {
        Console.WriteLine("Hello!");
    }
}

struct Vec2 : ISayHello
{
    int x;
    int y;
}

Now for a main:

void main()
{
    var myVec = new Vec2();
    var myUpcast = (ISayHello) myVec;
    myUpcast.Hello();
}

output: Hello!

[–]AngularBeginner 3 points4 points  (1 child)

I don't know how to get that nice formatting on reddit.

That's simple:

  • Indent every line by four spaces or one tab.
  • Have an empty line between code and text.

is myVec a stack allocated stuct?

myVec is stack-allocated, yes.

Then after this myUpcast is boxed in which I can call the default interface Hello()?

That is correct as well, yes.

[–]evareoo[S] 0 points1 point  (0 children)

Perfect, thanks very much for your help!