Saw this. Why the explicit cast to IDisposable? Is this just a shorthand to ensure that IDisposable is called on exiting the using block?
using (proxy as IDisposable)
{
string s = proxy.Stuff()
}
When GC tries to dispose of any un-referenced object, if the object has destructor GC has to copy it from current version to next and then call destructor. It adds overhead on GC. This is why we need IDisposable implementation.
By default, the garbage collector automatically calls an object's finalizer before reclaiming its memory. However, if the Dispose method has been called, it is typically unnecessary for the garbage collector to call the disposed object's finalizer.
IDisposable is an interface that contains a single method, Dispose(), for releasing unmanaged resources, like files, streams, database connections and so on.
You can call the IDisposable. Dispose() method from the finally block of a try/finally statement. By using the finally block, you can clean up any resources that are allocated in a try block, and you can run code even if an exception occurs in the try block.
This "trick", if you can call it that, is most likely due to proxy
being of a type that the compiler can't verify really implements IDisposable
.
The nice thing about the using
directive, is that if the parameter to it is null
, then no call to Dispose
will be done upon exiting the scope of the using
statement.
So the code you've shown is actually short-hand for:
var disposable = proxy as IDisposable;
try
{
string s = proxy.Stuff();
}
finally
{
if (disposable != null)
disposable.Dispose();
}
In other words, it says "if this object implements IDisposable, I need to dispose of it when I'm done with the following piece of code."
This could be required if you are given a proxy
instance from somewhere and its static type does not implement IDisposable
but you know that the real type may do and you want to make sure it will be disposed e.g.
public class Proxy : ISomeInterface, IDisposable
{
...
}
private ISomeInterface Create() { ... }
ISomeInterface proxy = Create();
//won't compile without `as`
using(proxy as IDisposable)
{
...
}
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