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.
XmlDataSource
in a using statement?try
/catch
/finally
in the lower one and a using
in the upper one?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;
}
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.