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

dashnick picture dashnick · Jan 4, 2016 · Viewed 8.3k times · Source

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();            
        }
    }
}

Answer

D Stanley picture D Stanley · Jan 4, 2016

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.