.NET Frameworkの管理下にない(アンマネージド)リソースを使用する型は、Dispose()
メソッドによって明示的に解放すべきである。Dispose()
メソッドをもつ型を使うときに、Dispose()
を実行するのは あなたの 責任である。Dispose()
が必ず呼ばれるようにする最良の方法は、using
文を使うか、try/finally
ブロックを使うかである。
public void ExecuteCommand(string connectionString,
string command)
{
using (var connection = new SqlConnection(connectionString))
using (var sqlCommand = new SqlCommand(command, connection))
{
connection.Open();
sqlCommand.ExecuteNonQuery();
}
}
同様の処理をtry/finally
で書くと以下のようになる。
public void ExecuteCommand(string connectionString,
string command)
{
SqlConnection myConnection = null;
SqlCommand myCommand = null;
try
{
myConnection = new SqlConnection(connectionString);
myCommand = new SqlCommand(command, myConnection);
myConnection.Open();
myCommand.ExecuteNonQuery();
}
finally
{
myConnection?.Dispose();
myCommand?.Dispose();
}
}
using
はコンパイル時の型がIDisposable
を実装している場合にのみ利用可能で、任意の型に対して利用できるわけではない。
以下のように、using
をキャストと共に使うと、(1) objがIDisposable
を実装している場合は、using
文が実行される (2) objがIDisposable
を実装していない場合は、using
文は実行されない という結果になる。
object obj = Factory.CreateResource();
using (obj as IDisposable)
WriteLine(obj.ToString());