Scott Hanselman

Today's Minor Complaint...

November 06, 2003 Comment on this post [5] Posted in XML
Sponsored By

Why is this OK:

using (StringReader sr = new StringReader(response))
{
   try
   {
      retVal = xs.Deserialize(sr);
   }
    //yada yada yada

}

Why and this isnt?

using (XmlTextReader xr = new XmlTextReader(new StringReader(response), /*...yada yada...*/)
{
   try
   {
      retVal = xs.Deserialize(sr);
   }
    //yada yada yada

}

Because StringReaders derive from System.IO.TextReader which implements IDisposable and that's what the using keywords cares about.  XmlTextReader derives from the abstract XmlReader, and noone implements IDisposable. I suppose this has something to do with closing streams in the right order, blah blah.  Either way, it was a minor sadness today.

Poop.

About Scott

Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. He is a failed stand-up comic, a cornrower, and a book author.

facebook twitter subscribe
About   Newsletter
Hosting By
Hosted in an Azure App Service
November 06, 2003 22:36
hi scott, what about this:

using System;
using System.Xml;

class DisposableXmlTextReader : XmlTextReader, IDisposable {
public void Dispose() {
base.Close();
}
}

I bet the formatting is going to get beaten up, but you get the idea. XmlTextReader is not sealed, so this should work. Or should it?
Ben
November 07, 2003 12:09
That's a bit too far I think. Perhaps this is cleaner:

using (StringReader s = new StringReader(response))
{
XmlTextReader xr = new XmlTextReader(s);

...
}

You don't care about IDisposable on XmlTextReader if all you want is the StringReader to be ditched properly.

Dave
November 08, 2003 21:06
True on both counts...I was just complaining basically that anything that was a "Reader" wasn't Disposable...I've gotten REALLY used to using the "using" keyword, and I prefer it over explicit close() calls.

Of course, I don't care so much as to make a separate derived class, but thanks for the thoughts! :)
November 12, 2003 7:20
FYI, I'm PM for XmlReader, and this was an oversight and is fixed in v2. If you have PDC bits, I believe that copy of frameworks already has the fix -- obviously you would not use this for production work, but the point is we are aware of the problem and are fixing it in v.Next. Thanks!
February 16, 2006 22:51
Just found your post while googling for the reason why this wasn't implemented. I'm using V2 and it's definitely NOT fixed in V2. So I had to implement this:

def auto_close(obj)
yield obj if block_given?
obj.Close
end

...

auto_close(XmlTextReader.new(path)) do |r|
while r.Read
puts r.LocalName if r.NodeType == XmlNodeType::Element
end
end

Isn't Ruby great? :)

Comments are closed.

Disclaimer: The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.