Search code examples
c#structinterfacevalue-typeboxing

Structs, Interfaces and Boxing


Possible Duplicate:
Is it safe for structs to implement interfaces?

Take this code:

interface ISomeInterface
{
    public int SomeProperty { get; }
}

struct SomeStruct : ISomeInterface
{
    int someValue;

    public int SomeProperty { get { return someValue; } }

    public SomeStruct(int value)
    {
        someValue = value;
    }
}

and then I do this somewhere:

ISomeInterface someVariable = new SomeStruct(2);

is the SomeStruct boxed in this case?


Solution

  • Yes, it is. Basically whenever you need a reference and you've only got a value type value, the value is boxed.

    Here, ISomeInterface is an interface, which is a reference type. Therefore the value of someVariable is always a reference, so the newly created struct value has to be boxed.