Mike-Ward.Net

Calling IDisposable through Interfaces that do not require IDisposable

How do you call IDisposable.Dispose() when your interface does not inherit from IDisposable but your implementation does? This happens more often than you might think, particularly when code generation is involved. For example, when Visual Studio generates service proxies for WCF service contracts, the generated ServiceClientProxy derives from System.ServiceModel.ClientBase, which can contain an auto-generated IDisposable depending on the interface constructs.

Of course you can always test for IDisposable by casting like below.

SomeInterface someInterface = SomeInterfaceFactory();

try
{
    someInterface.Bla().Bla().Bla();
}

finally
{
    if (someInterface is IDisposable)
        ((IDisposable)someInterface).Dispose();
}

This is straightforward and I think most programmers grok the construct. However, there is another way.

SomeInterface someInterface = SomeInterfaceFactory();

using (someInterface as IDisposable)
{
    someInterface.Bla().Bla().Bla();
}

This essentially generates the same code as the first example. The compiler keeps an internal variable to the object returned by someInterface as IDisposable and checks it against null before calling Dispose().

Either way works but in more complex code scenarios the using syntax can be less noisy and reduce the number of braces required.

← newer older →
.Net, Technology, Life, Whatever

Recent Posts

How to Choose the Right VPN Service
Two Handy Command Line Scripts
Tweetz 1.3.2
Tweetz 1.3 Release
Mithril Rising
Tweetz Release 1.2.4 - Screen Off Detection
Tweetz Desktop Support for 280 Characters
More... (1084)

Donate