Today's Minor Complaint...
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.
About Newsletter
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
Of course, I don't care so much as to make a separate derived class, but thanks for the thoughts! :)
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.
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?