I’m running a full code analysis on my project, and it says it has 500 issues. I’ve boiled it down to 300 now, but I’m struggling with an issue I can’t seem to find a solution for.
The rule CA2000 states:
If a disposable object is not explicitly disposed before all references to it are out of scope, the object will be disposed at some indeterminate time when the garbage collector runs the finalizer of the object. Because an exceptional event might occur that will prevent the finalizer of the object from running, the object should be explicitly disposed instead.
More information on the rule can be found on the page linked to above.
The code that the rule is failing on is this:
internal Window(Game game, Control parent, string title, bool visible)
: base(game, parent, visible, new ScreenspaceRectangle(game, Color.Black, Vector.Zero, Vector.Zero))
{
}
And the description is:
CA2000 : Microsoft.Reliability : In method ‘Window.Window(Game, Control, string, bool)’, call System.IDisposable.Dispose on object ‘new ScreenspaceRectangle(game, Color.Black, Vector.Zero, Vector.Zero)’ before all references to it are out of scope.
I understand that this issue can be resolved normally by using a “using” statement around the object being created, to make sure that it is always properly disposed. But how do I solve it in this case?
Assuming that the
Windowclass is your custom class, you should ensure that the base class constructor is storing the reference of ScreenspaceRectangle if it requires it outside the constructor and it implementsIDisposableand disposes the instance of ScreenspaceRectangle in theDisposemethod.Otherwise ensure that the object is being disposed in the base class constructor.