Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing IDisposable - Disposable Fields vs. Disposable Properties

Tags:

c#

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?

like image 968
Mejwell Avatar asked Nov 17 '14 16:11

Mejwell


2 Answers

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.

like image 93
Justin Niessner Avatar answered Sep 29 '22 06:09

Justin Niessner


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)

like image 34
SLaks Avatar answered Sep 29 '22 06:09

SLaks