Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET: Disposing a HashAlgorithm object

Objects that derive from HashAlgorithm such as MD5CryptoServiceProvider have a Dispose() method, but it's private. Instead it has a Clear() method which "Releases all resources" used by it.

WTF?

Is this how to correctly dispose of a HashAlgorithm then?

var hasher = new MD5CryptoServiceProvider();

byte[] hashCode = hasher.ComputeHash(data);

hasher.Clear();

Someone wanna explain this one to me? :)

like image 959
core Avatar asked Apr 17 '09 18:04

core


2 Answers

While the Dipose() method is private, if you cast it to IDisposable you can gain access to it. As others have said, though, Clear() will call it for you.

A better approach, however, is to enclose the declaration and and assignment of the variable in a using() block:

byte[] hashCode;

using(var hasher = new MD5CryptoServiceProvider())
{
    hashCode = hasher.ComputeHash(data);
}
like image 142
Adam Robinson Avatar answered Oct 21 '22 04:10

Adam Robinson


Looking with Reflector, the Clear method of HashAlgorithm simply calls the private Dispose method. The reason for exposing a method with name Clear was probably just that the designers of the class thought it would be a more suitable name for a hash algorithm. You see similar styles within other parts of the BCL, such as Close for System.IO.Stream. Also, best practice here is to use a using block, which will automatically call the private Dispose method when it's finished.

like image 44
Noldorin Avatar answered Oct 21 '22 04:10

Noldorin