Returning disposable object and getting CA2000 warning

I am trying to return XMLNodeReader to another function but getting CA2000 warning

XmlNodeReader obj =new XmlNodeReader(section);
return ser.method(obj);

If I use the following code, will it work properly? The warning is supressed but not sure if it will affect the logic or not.

XmlNodeReader tempObj =new XmlNodeReader(section);
XmlNodeReader retObj=null;
retObj = tempObj;
tempObj.Dispose();
return ser.method(retObj);
Jon Skeet
people
quotationmark

Well we have no idea what ser.method does, but passing a disposed object into method seems like a bad idea to me. Basically, your "fix" is bad.

There are three possibilities here (and probably others, but these are the main ones):

  • ser.method disposes of its parameter itself. (That's probably a bad idea, but it might do.) In that case, your original code is fine.
  • ser.method doesn't dispose of its parameter, but it returns something that relies on the reader still not being disposed
  • ser.method doesn't dispose of its parameter, and returns something that doesn't need the reader to stay open

I'm hoping the last of these is the case, in which case you should change your code to:

using (XmlNodeReader reader = new XmlNodeReader(section))
{
    return ser.method(reader);
}

people

See more on this question at Stackoverflow