Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Code Analysis Warning CA2213 - Call Dispose() on IDisposable backing field

Wanted to post this, even though I figured it out as I was writing the question. Will post answer below.

Getting the following warning with VS Code Analysis:

Warning CA2213 'DBConn' contains field 'DBConn.k__BackingField' that is of IDisposable type: 'SqlConnection'. Change the Dispose method on 'DBConn' to call Dispose or Close on this field.

But my code does call Dispose() on the DBConn property. Does it not on the backing field? I have other instances like this - where I am disposing of where the compiler does not throw this warning. This is the code below:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;    

namespace TheProgramSpace
{
    public sealed class DBConn : IDisposable
    {
        // class containing the database and its connection
        public SqlConnection TheConn { get; }
        public string DbPath { get; }
        public string DbName { get; }


        public DBConn(ProgInstance FPI)
        {
            // constructs new SQLConnection            
            DbPath = FPI.dbPath;
            DbName = FPI.dbName;

            string connString = "Data Source = " + DbPath + "; Initial Catalog =" + DbName + "; Integrated Security = True; "
              + "Connect Timeout = 30; Encrypt = False; TrustServerCertificate = False; "
              + "ApplicationIntent = ReadWrite; MultiSubnetFailover = False";                     

            TheConn = new SqlConnection(connString);

        }

        public void Dispose()
        {            
            TheConn.Dispose();            
        }
    }
}
like image 384
dashnick Avatar asked Jan 04 '16 00:01

dashnick


2 Answers

There is not a problem with your code. Dispose will be called on the underlying backing field. This is a known bug in FxCop that surfaced with the introduction of "getter-only" automatic properties which were introduced in C# 6. For now, you can either suppress the warning with an attribute on the class or just ignore it until it's fixed in FxCop.

like image 175
D Stanley Avatar answered Nov 10 '22 21:11

D Stanley


The reason is that TheConn, because it did not have a set accessor, was read-only. Changing the property declaration to

public SqlConnection TheConn { get; private set; }

solved the problem.

like image 17
dashnick Avatar answered Nov 10 '22 21:11

dashnick