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

VSColorOutput for VS 2017 Released
Quick ReSharper tip for inline templates
NoSQL vs. NewSQL: What's the Difference?
Exploring Mithril, A JavaScript Framework for Building Brilliant Applications
Tweetz 1.1
Tweetz Desktop 1.0
Tweetz 0.11 Released
More... (1073)

Donate with PayPal