If my struct implements IDisposable will it be boxed when used in a using statement?
Thanks
Edit: this timedlock is a struct and implements Idisposable. http://www.interact-sw.co.uk/iangblog/2004/04/26/yetmoretimedlocking
Edit 2: Looking at the IL it seems If your struct exposes Dispose() as public, the compiler calls Dispose when an instance of the struct goes out of scope if you forget to call Dispose() (for example, you are not using the "using" statement)?
Dispose() will not be called automatically. If there is a finalizer it will be called automatically. Implementing IDisposable provides a way for users of your class to release resources early, instead of waiting for the garbage collector.
in a class, you should implement IDisposable and overwrite the Dispose method to allow you to control when the memory is freed. If not, this responsibility is left to the garbage collector to free the memory when the object containing the unmanaged resources is finalized.
The Dispose method is automatically called when a using statement is used. All the objects that can implement the IDisposable interface can implement the using statement. You can use the ildasm.exe tool to check how the Dispose method is called internally when you use a using statement.
IDisposable is defined in the System namespace. It provides a mechanism for releasing unmanaged resources. When your application or class library encapsulates unmanaged resources such as files, fonts, streams, database connections, etc, they should implement the IDisposable interface or the IAsyncDisposable interface.
Per Eric Lippert:
A call to IDisposable.Dispose on a struct is generated as a constrained virtual call, which most of the time does NOT box the value.
A constrained virtual call on a value type only boxes the value if the virtual method is NOT implemented by the type. The only circumstances under which a virtual method can be unimplemented by the value type is when the method is, say, ToString, and implemented by the base class, System.ValueType.
See section 2.1 of Partition III of the CLI documentation for more detail.
This is a duplicate of When does a using-statement box its argument, when it's a struct?
UPDATE: This question was the subject of my blog in March of 2011. Thanks for the great question.
A few points:
((IDisposable)resource).Dispose();
which is clearly a boxing conversion. We do not actually generate the boxing conversion. Since most of the time this is what you want anyway, we're not losing any sleep over it.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With