CA2000 DisposeObjectsBeforeLosingScope

Why does code such as this display a false positive on the dispose when the dispose will always execute?

SqlTransaction txn =null;

SqlCommand addFingerprint =null;

try {

addFingerprint =newSqlCommand("xxxxxxxxxxx xxxxxxxxxxxxx xxxxxxxxxxx");

conn.Open();

txn = conn.BeginTransaction();

addFingerprint.Transaction = txn;

SqlContext.Pipe.ExecuteAndSend(addFingerprint);();

txn.Commit();

}catch (SqlException) {

txn.Rollback();

throw;

}finally {

if (conn !=null && conn.State ==ConnectionState.Open) conn.Close();

if (addFingerprint !=null) addFingerprint.Dispose();

}

[1771 byte] By [DaveRyan] at [2008-1-4]
# 1

Have you checked the message to see which disposable variable is causing the violation? SqlTransaction is disposable, but it isn't being disposed in your sample code.

BTW, a SqlTransaction will automatically rollback on disposition if it hasn't been committed, so there's no need to catch simply to rollback. A cleaner usage pattern would be something like the following:

Code Snippet

using (SqlTransaction transaction = connection.BeginTransaction())

{

// ...

transaction.Commit();

}

NicoleCalinoiu at 2007-9-26 > top of Msdn Tech,Visual Studio Team System,Visual Studio Code Analysis and Code Metrics...

Visual Studio Team System

Site Classified