CA1850: Prefer static HashData
method over ComputeHash
Property | Value |
---|---|
Rule ID | CA1850 |
Title | Prefer static HashData method over ComputeHash |
Category | Performance |
Fix is breaking or non-breaking | Non-breaking |
Enabled by default in .NET 9 | As suggestion |
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.
Suppress a warning
If you just want to suppress a single violation, add preprocessor directives to your source file to disable and then re-enable the rule.
#pragma warning disable CA1850
// The code that's violating the rule is on this line.
#pragma warning restore CA1850
To disable the rule for a file, folder, or project, set its severity to none
in the configuration file.
[*.{cs,vb}]
dotnet_diagnostic.CA1850.severity = none
For more information, see How to suppress code analysis warnings.