There is an existing class from a third-party library I want to reuse, but it does not implement some of the required interfaces. I'm thinking of wrapping it inside a struct to fulfill the required interfaces (basically like how Scala does it). The reason why I prefer struct over class for this use case is because it only stores one thing: the wrapped object, and it probably won't incur performance penalties? But I'm not sure if boxing would occur if I pass a struct to some method that takes in an interface? And are there any other drawbacks about this approach?
- 4If you access a struct via an interface reference it will be boxed, negating most of the benefits.Mike Zboray– Mike Zboray2013-09-27 06:06:35 +00:00Commented Sep 27, 2013 at 6:06
3 Answers
Microsoft gives very clear and straightforward reasons where you should use a struct instead of a class:
√ CONSIDER defining a struct instead of a class if instances of the type are small and commonly short-lived or are commonly embedded in other objects.
X AVOID defining a struct unless the type has all of the following characteristics:
- It logically represents a single value, similar to primitive types (int, double, etc.).
- It has an instance size under 16 bytes.
- It is immutable.
- It will not have to be boxed frequently.
https://msdn.microsoft.com/en-us/library/ms229017.aspx
And seems like it's not your case. And btw yes, boxing will occur if you pass a struct to a method that takes an interface. Also take into account that structures don't support inheritance and they can't have explicit parameterless constructors.
Comments
Yes you can use struct in this case, if you do not want both interface implementation(existing + extra you want to add) at a time. There wont be any overhead of wrapping because struct will store only reference not the whole object. Because objects will always be accessed via reference i.e. stored on heap. So there won't be any performance penalties. However it is not recommended practice
However if you have cases where you can use both interface implementation, you should define a new class derived which will have a variable to store the object of base class. In this way, you can use object of derived class and keep variable pointing to base class object as null.
Refer http://adarshdchaurasia.wordpress.com/2013/08/12/decorator-design-pattern/ to know the details of implementaion.
Also refer Can you have a class in a struct?
7 Comments
Much simpler would be to directly inherit the 3rd-party class in your code and then implement the interface you desire on this derived class. No boxing; only references will be passed.