0

Do I really need to dispose the writer below?

DataContractSerializer _serialier...
var actual = new XmlDocument();
using (var writer = actual.CreateNavigator().AppendChild())
    _serialier.WriteObject(writer, myObj);

If not then the code is simplified to:

DataContractSerializer _serialier...
var actual = new XmlDocument();
_serialier.WriteObject(actual.CreateNavigator().AppendChild(), myObj);
Schultz9999
  • 8,717
  • 8
  • 48
  • 87

1 Answers1

1

If the object implements IDisposable, then you should call Dispose on it when you're done.

If you don't do that, then your code is dependent on the assumption that you don't need to do it. What happens when your code is later refactored such that the XmlWriter being used is one that holds on to some resource?

John Saunders
  • 160,644
  • 26
  • 247
  • 397
  • If the writer passed in then it's the responsibility of the caller to dispose it, isn't it? It would be a rather bad idea to call dispose in that case. – Schultz9999 Apr 20 '11 at 23:18
  • 1
    Good catch. Wording corrected. Note that, without tracing through the code, it's not possible to know that there are _no_ resources to dispose of in the current case. – John Saunders Apr 20 '11 at 23:49
  • corrected wording makes my comment irrelevant :) Thanks though, I see your point. As a matter of fact I indeed apply 'using' everywhere where I see/realize there is IDisposable. For this particular case, I am just wondering what kind of disposable resources may XmlDocument hold on to if it wasn't created from a stream, file, etc. I guess it's declared like that to cover all possible cases and there might be some exceptions when Dispose doesn't do much. – Schultz9999 Apr 25 '11 at 16:05
  • @Schultz: no, it's just that AppendChild returns an XmlWriter, and that implements IDisposable. You have no way to know how AppendChild is implemented. It could decide to write the element to disk, then position a FileStream to the correct location, then create an XmlWriter off of the FileStream. Unlikely, but you would never know if they changed the code to do that. – John Saunders Apr 25 '11 at 17:25