Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C#, should I use struct to wrap an object in order to fulfill additional interfaces?

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?

like image 736
shengmin Avatar asked Mar 23 '23 06:03

shengmin


1 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.

like image 52
Olexander Ivanitskyi Avatar answered Mar 24 '23 21:03

Olexander Ivanitskyi