Lately I was refactoring a manager class which used internally a private struct to hold instances belonging together in a dictionary. Some referenced instances hold in this struct were disposable, thus implementing the IDisposable interface. The thought of implementing IDisposable on the internal struct came across my mind but then I quickly asked myself what happens with the struct if you implement IDisposable in .NET. I want to present the result of my research in this article.
Because structs are ValueTypes they are often preferred as suitable type for representing lightweight objects such as Points, Rectangles or Colors. Thus structs offer in some cases a less expensive representation of types when dealing with a large number of the same type. Although this advantage might be destroyed if you let the struct implement IDisposable. If you call the dispose method on the struct, the .NET runtime will effectively box your struct into an object type before the dispose method is called. This forces the runtime to assign additional heap space for every struct that needs to be boxed.
This disadvantage can only be overcome if you are declaring your struct in a using statement. The using statement only implicitly calls the dispose method. Calling the dispose method implicitly on the struct will not lead to boxing of the struct type to an object.
As conclusion I recommend to strongly think about implementing IDisposable or event other interfaces on structs because of the fact that boxing and unboxing might occur, thus loosing the performance and cost effectiveness a struct could offer. Only if you can assure that your struct is internally used and you can guarantee that the client of your struct will only use your struct in using statements you might consider implementing IDisposable. Happy coding!