Josh Kitchens
Josh Kitchens

Reputation: 1110

Do interfaces with struct properties result in boxing?

Let's say I have some struct and some interface which, among other things, exposes that struct as a property:

public struct MyStruct{
    public readonly string Hello;

    public MyStruct(string world){
        Hello = world;
    }
}

public interface IMyInterface{
    MyStruct myStruct{ get; set; }
}

And within my application, an object which implements that interface is created and passed into some method:

public void MyMethod(IMyInterface interface){
    var structContents = interface.myStruct;
    Console.WriteLine(structContents.Hello);
}

My question is: when I'm packing that struct value into the interface and passing it around my application, is that struct being boxed and then being unboxed later when I access it in MyMethod? Or is there any other boxing/unboxing or other issue going on behind the scenes with such a design?

Upvotes: 0

Views: 312

Answers (1)

Charles Mager
Charles Mager

Reputation: 26223

Per the docs:

Boxing is the process of converting a value type to the type object or to any interface type implemented by this value type.

You're not doing either of those things with myStruct, so there's no boxing here.

Upvotes: 3

Related Questions