Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can a dispose method be hidden?

Tags:

c#

interface

I'm using a third party API dll, bloomberg SAPI for those who know / have access to it.

Here's my problem:

[ComVisible(true)]
public interface IDisposable     
{ //this is from mscorlib 2.0.0.0 - standard System.IDisposable
    void Dispose();
}

public abstract class AbstractSession : IDisposable {}//method signatures and comments

public class Session : AbstractSession {} //method signatures and comments (from assembly metadata)

All of the above is from the F12 / Go to definition / object browser in VS2010. Now when i try and use this code:

(new Session()).Dispose();

This does not compile... standard compiler error - no definition / extension method 'Dispose' could be found.

How is this possible??? They've made an assembly and explicitly edited it's metadata?

I don't know if it's legally possible to hide (to exclusion) a public method....

like image 663
Vivek Avatar asked Aug 02 '13 18:08

Vivek


1 Answers

This is called explicit interface implementation. The class is written like:

class Session : IDisposable {
    void IDisposable.Dispose() {
        // whatever
    }
}

You can only call it if your variable is of type IDisposable, like:

IDisposable mySession = new Session();
mySession.Dispose();

Or by casting:

((IDisposable)mySession).Dispose();

Or with a using statement, which automatically calls Dispose when it completes (this is specific only to IDisposable, and is generally a best practice for disposing any object which implements this interface):

using (var session = new Session()) { }
like image 136
Joe Enos Avatar answered Oct 15 '22 17:10

Joe Enos