0

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
  • 1,421,763
  • 867
  • 9,128
  • 9,194
user3386619
  • 31
  • 1
  • 5
  • Well we have no idea what `ser.method` does, but passing a disposed object into `method` seems like a bad idea to me. – Jon Skeet May 31 '17 at 08:33
  • CA2000 sometimes give you false positives but is *usually* an indication of something that looks odd so it's not all bad. You need to decide if the area of the code that constructs the object also owns it, or whether you pass ownership to whoever receives the object. Once you've decided that you can look into how to get rid of the warning. – Lasse V. Karlsen May 31 '17 at 08:35
  • Note that in some cases, if you're creating a "factory method", you may get rid of the warning by simply naming the method better, try "Get" vs. "Create" as a prefix for the method name, see if any of them helps. – Lasse V. Karlsen May 31 '17 at 08:35

1 Answers1

2

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);
}
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Hi Jon. ser.method is Deserialize(XmlReader xmlReader) method of System.XML. – user3386619 May 31 '17 at 08:40
  • @user3386619: So why didn't use say that in the original question, so we wouldn't have to guess? Ideally, provide a [mcve] when asking a question. – Jon Skeet May 31 '17 at 08:45
  • Apologies for not following the rule while posting. I will keep this in mind from now onwards. Thanks for your answer. :-) – user3386619 May 31 '17 at 08:59