Returning XmlTextReader object, can I call .Close()

1k views Asked by At

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?

Thanks

1

There are 1 answers

5
Alexei Levenkov On BEST ANSWER

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;
}

Usage:

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.