I am using some XmlReader and XmlWriter object to do some needed work on strings inside some try...catch blocks.
I know that using the notation using (XmlReader NewReader = XmlReader.Create(...)) is the prefered syntax, but I don’t really like that so I am also appending finally blocks and executing NewReader.Close(); and NewWriter.Close();.
However, code analysis is complaining that these objects aren’t being disposed, thus forcing me to somehow call Dispose() method.
The problem is that in these classes the Dispose() method is implemented explicitly, so I have to use ((IDisposable)(NewReader)).Dispose(); and ((IDisposable)(NewWriter)).Dispose();.
Are there any drawbacks to this technique?
The C#
usingstatement will always callDisposefor you. It roughtly translates to the following:So wrapping it in
finallyyouself doesn’t add any value. AlthoughCloseandDisposeare often equivalent, it is not always the case. Because of this FxCop is right, you should always callDisposeand when you do this (or let theusingstatement do this), there is no reason to callClosemanually.