Reputation: 2112
In converting .NET Core project to .NET Framework, one thing notice is using Hashcode now needs to be converted something equivalent. As can be read, Hashcode is specific to .NET core versions and some extensions.
https://learn.microsoft.com/en-us/dotnet/api/system.hashcode?view=dotnet-plat-ext-3.1
Wonder what would be close enough in terms of usages in .NET Framework, if there is any in-built object type.
Upvotes: 4
Views: 7714
Reputation: 13207
No need to reinvent the wheel ‒ on .NET Standard 2.0 (and thus .NET Framework too) you can use the Microsoft.Bcl.HashCode nuget package, which provides the standard System.HashCode
implementation for you to use. This is the equivalent (indeed it is more than that) you are looking for.
Upvotes: 6
Reputation: 10588
EDIT:
System.HashCode
is available in .NET Core too. You can use HashCode.Combine
for this purpose, see: https://learn.microsoft.com/en-us/dotnet/api/system.hashcode?view=netcore-2.1
var combined = HashCode.Combine("one", "two");
(previous answer below)
The long and thorough answer(s) can be found here: https://stackoverflow.com/a/34006336/25338
If you just want a simple answer, you can combine the object hashes in a new structure (tuple, anonymous class, etc), and call GetHashCode()
on the result.
e.g.
public override int GetHashCode() {
return new { MyField1, MyField2 }.GetHashCode();
}
Elaborating on the answer linked above, you could of course, if you would like to make it easier (?) create a common static helper class that does the work for you:
public class MyHashCode
{
public static int Hash(params object[] values)
=> CustomHash(1009, 9176, values.Select(v => v.GetHashCode()).ToArray());
// From answer https://stackoverflow.com/a/34006336/25338
public static int CustomHash(int seed, int factor, params int[] vals)
{
int hash = seed;
foreach (int i in vals)
{
hash = (hash * factor) + i;
}
return hash;
}
}
and call it like this:
public class UnitTest1
{
[Fact]
public void Test1()
{
string s1 = "yezz";
string s2 = "nope";
var hash = Utils.MyHashCode.Hash(s1, s2);
}
}
Upvotes: 8