Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast type to IDisposable - Why?

Tags:

c#

idisposable

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()                                    
}
like image 489
AJM Avatar asked Jan 14 '11 20:01

AJM


People also ask

Why do we use IDisposable?

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.

Is IDisposable called automatically?

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.

What is System IDisposable?

IDisposable is an interface that contains a single method, Dispose(), for releasing unmanaged resources, like files, streams, database connections and so on.

Which of the following keywords can you use with an object implementing IDisposable to ensure the object cleans up resources as soon as possible?

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.


2 Answers

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

like image 157
Lasse V. Karlsen Avatar answered Oct 28 '22 15:10

Lasse V. Karlsen


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)
{
    ...
}
like image 35
Lee Avatar answered Oct 28 '22 17:10

Lee