ganders ganders - 1 year ago 104
C# Question

Returning XmlTextReader object, can I call .Close()

I'm in a bind right now trying to find the source of a problem. Our exception handling is lacking, so I'm kind of guessing on where the error is coming from. Here's my question, if a method returns an XmlTextReader object, does that object become null if it's wrapped in a try/catch/finally where the finally block does the .Close() method?

If yes, how can I dispose of those resources properly, I know there isn't a .Clone() or .Copy() method, is there another way to accomplish this? Should I even care about disposing of XmlTextReader and XmlReader objects?


Answer Source

You must not be closing/disposing XmlReader before returning it to the caller.

And no, Dispose/Close do not assign null to an object - they simply asks the object to release whatever resources it feels need to be released.

XmlReader GetReader()
   XmlRead reader = ....

   // DO NOT dispose/close reader here with 
   // reader.Dispose() or using(reader){...}

   return reader;


using(var reader = GetReader()) {...}

Note that many types safeguard against access to data after Dispose called. Approach used by many classes in .Net is to fail all calls to access state of the object with ObjectDisposedException after Dispose is called.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download