tabs ↹ over ␣ ␣ ␣ spaces

by Jiří {x2} Činčura

Easier GetHashCode implementation in .NET Core 2.1

5 Jun 2018 .NET, .NET Core, .NET Standard, C#

Writing correct GetHashCode implementation is difficult. I know you’ve written it before and simple xor-ing looks fine. But trust me, it’s more than that. Especially if you want your implementation to be solid and useful for hash-tables etc. And .NET was not helping in any way. Until now.

In .NET Core 2.1 a new struct was added. It’s called System.HashCode and it makes generating hash codes super convenient. Have a look at this class.

class Person
{
	public string FirstName { get; set; }
	public string LastName { get; set; }

	public override int GetHashCode() => HashCode.Combine(FirstName, LastName);
}

That’s all I have to do! Proper hash code implementation. I don’t have to care about nulls, distribution, uniqueness, speed, … Of course one should, for solid code, also provide Equals override (and maybe also IEquatable<T> implementation).

Sadly this struct is not part of .NET Framework 4.7.2 (or any older) nor it’s available on NuGet. Not talking about .NET Standard 2.0 (or 2.1?). But hope is not lost. It might become available on NuGet as an OOB package.