interface implementation

  • Thread starter Thread starter stevenkobes
  • Start date Start date
S

stevenkobes

If s has type System.IO.Stream, why does ((IDisposable) s).Dispose()
work while s.Dispose() fails? The error is:

error CS0117: 'System.IO.Stream' does not contain a definition for
'Dispose'

This seems impossible since Stream implements IDisposable.
 
It doesn't work because implementers of interfaces don't have to expose
their members publically. The Stream class does not expose the Dispose
method publically, which is why you need the cast.

Hope this helps.
 
Nicholas said:
It doesn't work because implementers of interfaces don't have to expose
their members publically. The Stream class does not expose the Dispose
method publically, which is why you need the cast.

Really?

class Foo : IDisposable {
protected void Dispose() {}
}

error CS0536: 'Foo' does not implement interface member
'System.IDisposable.Dispose()'. 'Foo.Dispose()' is either static, not
public, or has the wrong return type.
 
Yes, really:

class Foo : IDisposable
{
void IDispose.Dispose()
{
}
}
 
That should be:

class Foo : IDisposable
{
void IDisposable.Dispose()
{
}
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top