tabs ↹ over ␣ ␣ ␣ spaces

by Jiří {x2} Činčura

Easier GetHashCode implementation in .NET Core 2.1

5 Jun 2018 1 mins .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.

Profile Picture Jiří Činčura is .NET, C# and Firebird expert. He focuses on data and business layers, language constructs, parallelism, databases and performance. For almost two decades he contributes to open-source, i.e. FirebirdClient. He works as a senior software engineer for Microsoft. Frequent speaker and blogger at