CA1850: Prefer static HashData method over ComputeHash

Value
Rule ID CA1850
Category Performance
Fix is breaking or non-breaking Non-breaking

Cause

An instance of a type that derives from HashAlgorithm is created to call its ComputeHash method, and that type has a static HashData method.

Rule description

Static HashData methods were introduced in .NET 5 on the following types:

These methods help simplify code in cases where you just want to hash some data.

It's more efficient to use theses static HashData methods than to create and manage a HashAlgorithm instance to call ComputeHash.

How to fix violations

In general, you can fix the rule by changing your code to call HashData and remove use of the HashAlgorithm instance.

public bool CheckHash(byte[] buffer)
{
  using (var sha256 = SHA256.Create())
  {
    byte[] digest = sha256.ComputeHash(buffer);
    return DoesHashExist(digest);
  }
}
Public Function CheckHash(buffer As Byte()) As Boolean
  Using sha256 As SHA256 = SHA256.Create()
    Dim digest As Byte() = sha256.ComputeHash(buffer)
    Return DoesHashExist(digest)
  End Using
End Function

The previous code can be changed to call the static HashData(Byte[]) method directly.

public bool CheckHash(byte[] buffer)
{
    byte[] digest = SHA256.HashData(buffer);
    return DoesHashExist(digest);
}
Public Function CheckHash(buffer As Byte()) As Boolean
  Dim digest As Byte() = SHA256.HashData(buffer)
  Return DoesHashExist(digest)
End Function

When to suppress warnings

It is safe to suppress a warning from this rule.

See also