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();


    if (someInterface is IDisposable)

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

SomeInterface someInterface = SomeInterfaceFactory();

using (someInterface as IDisposable)

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

Quick Tip - Clear ReSharper's Cache to Fix False Errors
Quick Tip - Refined GitHub
Vertical Layout for HTML Tables
Visual Studio 2017 Installer Quick Tip
VSColorOutput for VS 2017 Released
Quick ReSharper tip for inline templates
NoSQL vs. NewSQL: What's the Difference?
More... (1077)

Donate with PayPal