I was running VS2013's code analysis on one of my current projects, and came across "CA1001: Types that own disposable fields should be disposable." A simple example that generates the warning (presuming DisposableClass
implements IDisposable
) is:
class HasDisposableClassField
{
private DisposableClass disposableClass;
}
However, converting the field variable to a property no longer generates the warning, even if the circumstance is that the property will be instantiated by the class:
class HasDisposableClassProperty
{
private DisposableClass disposableClass { get; set; }
public HasDisposableClassProperty()
{
disposableClass = new DisposableClass();
}
}
In the first case it's clear that the class should implement the IDisposable pattern, and dispose of its disposableClass
field appropriately. My question: is the lack of a warning for the second case a limitation of the code analysis tool? Should the class still implement IDisposable and dispose of the property, despite the lack of a warning?
Yes, the lack of a warning is a limitation of the analysis tool.
You should definitely still implement IDisposable
and clean up after yourself assuming your IDisposable
properties aren't being injected from elsewhere.
Yes; you still need to dispose it.
Putting something in a property does not magically dispose it for you.
The missing warning is a bug on Code Analysis (it ignores the backing field because it's compiler-generated)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With