Search code examples
c#disposeusing-statement

How do I access a variable that I populate within a using block outside of that block?


I have an Xmlreader that I would like to load into an XMLDocument inside a 'using': However, the problem is that the XMLDocument gets disposed once finished (after xml.Load(reader)). I have tried including an int variable inside the 'using' and it also gets disposed. However, in the first 'using' where I create the 'result' string, it does not get disposed after leaving the statement. Why is that happening?

        HttpWebRequest req = WebRequest.Create(URL_GET.ToString()) as HttpWebRequest;
        string result = null;
        using (HttpWebResponse resp = req.GetResponse() as HttpWebResponse)
        {
            StreamReader reader = new StreamReader(resp.GetResponseStream());
            result = reader.ReadToEnd();
        }            
        using (XmlReader reader = XmlReader.Create(new StringReader(result)))
        {
            reader.ReadToFollowing("ops:output");
            XmlDocument xml = new XmlDocument();
            xml.Load(reader);
        }

Solution

  • xml doesn't get disposed; it simply goes out of scope, so the variable is not accessible any more - however, nothing has happened to the object it referred to. Simply declare xml outside of the using scope:

    XmlDocument xml;
    using (XmlReader reader = XmlReader.Create(new StringReader(result)))
    {
        reader.ReadToFollowing("ops:output");
        xml = new XmlDocument();
        xml.Load(reader);
    }
    // Now, xml exists here