Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to call Dispose?

Tags:

.net

c#-2.0

This one has confused me a little... Attempting to dispose of an XmlReader

XmlReader reader = XmlReader.Create(filePath);
reader.Dispose();  

Provides the following error:

'System.Xml.XmlReader.Dispose(bool)' is inaccessible due to its protection level

however the following is fine:

using(XmlReader reader = XmlReader.Create(filePath))
{
}

When I look at the definition in Reflector I can't understand why I can't call Dispose

XmlReader

Implementation of Dispose:

Dispose

Can anyone point out what I'm missing?

like image 795
Ian Avatar asked Mar 06 '12 11:03

Ian


1 Answers

The problem is that XmlReader uses explicit interface implementation to implement IDisposable. So you can write:

XmlReader reader = XmlReader.Create(filePath);
((IDisposable)reader).Dispose();

However, I'd strongly suggest using a using statement anyway. It should be very rare that you call Dispose explicitly, other than within another Dispose implementation.

EDIT: As noted, this is "fixed" in .NET 4.5, in that it exposes a public parameterless Dispose method as of .NET 4.5 as well as the explicit interface implementation. So presumably you're compiling against .NET 4.0 or earlier (perhaps .NET 2.0 given your tags) but using Reflector against .NET 4.5?

like image 155
Jon Skeet Avatar answered Oct 16 '22 12:10

Jon Skeet