0

In my extremely simplified code sample my Foo() method calls GetXmlDataSource() which returns an XmlDataSource. CA2000 says that I should Dispose() an XmlDatasource before losing scope.

  • Should I wrap each XmlDataSource in a using statement?
  • Should I use try/catch/finally in the lower one and a using in the upper one?
  • Do I effectively have two XmlDataSource objects, one in the upper method and one in the lower method?

I'm a little fuzzy on language behavior in this one and I want to be a good boy.

void Foo()
{
    XmlDataSource xds = GetXmlDataSource();
}

XmlDataSource GetXmlDataSource()
{
    XmlDataSource xmlDataSource = new XmlDataSource();
    return xmlDataSource;
}
Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
Kristopher
  • 819
  • 14
  • 31
  • 1
    your last question: no they are reference type so its only one. – M.kazem Akhgary Oct 23 '15 at 13:40
  • You should dispose the object in your `Foo` method when you're done with it. If code analysis complains about `GetXmlDataSource`, try naming it `CreateXmlDataSource` and see if it makes a difference. – Lasse V. Karlsen Oct 23 '15 at 13:41

2 Answers2

2

Should I wrap each XmlDataSource in a using statement?

If it goes out of scope inside that method, yes, you should. You can also use using on variables coming from other methods by the way.

Should I use try/catch/finally in the lower one?

Yes and no. The XmlDataSource shouldn't be disposed since you intend to use it in the other method. You should dispose it if you have an exception that will prevent the variable to be passed along.

Should I use using in the upper one?

Yes, you should. This code will do the job.

using (XmlDataSource xds = GetXmlDataSource())
{ }

Do I effectively have two XmlDataSource objects, one in the upper method and one in the lower method?

No, you have one. That is why you shouldn't dispose the lower one. There is a reference passed from one method to another.

Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
1

1) only wrap the final usage in a using. 2) no, a using is enough (note that the underlying implementation of using is a try/finally). 3) you have only one object instance.

GreatAndPowerfulOz
  • 1,767
  • 13
  • 19