4

I'm just looking for some advice from someone more experienced than me really (wont be hard).

The following code...

        XmlSerializer serializer = new XmlSerializer(typeof(Installation));
        using (var sw = new StringWriter()) {
            using (var xw = XmlWriter.Create(sw)) {
                serializer.Serialize(xw, Installation);
            }
            xmlResult = sw.ToString();
        }

has the following report in the code analysis...

CA2202 Do not dispose objects multiple times Object 'sw' can be disposed more than once in method 'Views_Commissioning_installationSubsidyForm.SaveInstall(string)'. To avoid generating a System.ObjectDisposedException you should not call Dispose more than one time on an object.: Lines: 766 nc1_DealerPortal installationSubsidyForm.aspx.cs 766

Can anyone explain how I'm disposing of 'sw' more than once? What am I doing wrong here?

Stuart
  • 1,544
  • 5
  • 29
  • 45
  • 1
    possible duplicate of [What is causing 'CA2202: Do not dispose objects multiple times' in this code and how can I refactor?](http://stackoverflow.com/questions/14706523/what-is-causing-ca2202-do-not-dispose-objects-multiple-times-in-this-code-and) – Jeroen Mostert Oct 21 '14 at 10:06

1 Answers1

1

StringWriter will be disposed by the XmlWriter, so by having 2 using statements it will get disposed twice change you code as below:

XmlSerializer serializer = new XmlSerializer(typeof(Installation));
var sw = new StringWriter()) 
using (var xw = XmlWriter.Create(sw)) 
{
    serializer.Serialize(xw, Installation);
    xmlResult = sw.ToString();
}
Ben Robinson
  • 21,601
  • 5
  • 62
  • 79
  • why is it getting disposed by XmlWriter? Just some clarification for my self. (Maybe because of the fact, that sw is used to create a XmlWriter Object?) – Dom84 Oct 21 '14 at 10:05
  • so, if I use an object with another object that is instantiated within a using statement, the first object will also be disposed? – Stuart Oct 21 '14 at 10:05
  • If `XmlWriter.Create()` fails, `sw` is not disposed. Code Analysis ought to complain about this one as well. – Jeroen Mostert Oct 21 '14 at 10:06
  • @Jeroen really? i thought it would be, because the using statement always uses a finally statement whether it errors or not, right? i thought that was the purpose of a using statement? – Stuart Oct 21 '14 at 10:08
  • 1
    In the code @BenRobinson posted, `xw` is always disposed -- but `sw` isn't necessarily, because it's not in any `using` block. Rather than disposing twice, this code potentially does not dispose at all (of course, for `StringWriter`, this is of no practical importance). – Jeroen Mostert Oct 21 '14 at 10:11
  • 1
    @Stuart: no, not necessarily. There are some object in .NET and other libraries which take ownership of disposable objects you give them. But there is no guarantee of this. You need to check each case individually. – Peter Duniho Oct 21 '14 at 10:38