A normal pattern to prevent CA2000 from warning about undefined locales is to use a temporary variable that will be deleted if something goes wrong, like:
Foo f = null; try { f = new Foo(); Foo result = f; f = null; return result; } finally { if (f != null) { f.Dispose(); } }
A bit verbose, but it works, and that makes sense. But how to apply the template to chain constructors, for example:
public HomeController ( IDataRepository db ) { this.repo = db ?? new SqlDataRepository(); } public HomeController ( ) : this(new SqlDataRepository()) { }
This code raises two CA2000 warnings, one for each constructor. The first thing I can get rid of is using the temp variable template. This is quite annoying since there is no way for a local user to get out of scope after creating it, but before it gets assigned to the member field, which will be cleared later. Therefore, I do not know what the CA problem is, but at least I know what to do to fix it.
But, as far as I can tell, there is no alternative way to write a second constructor call to introduce try / finally. The assigned field is read-only, so it should be set in the constructor. And C # will not allow you to call the chain of constructors anywhere, but directly in front of the body of the constructor. And, with regard to the second, the second warning is actually more legitimate - a call to the chain constructor can (theoretically, if it performed any actual work) cause an exception and leave the newly created parameter unchanged.
Of course, I can always just suppress this message (which CA2000 seems to need a lot), but if there is a real way to fix the problem, I would rather do it.