Easier GetHashCode implementation in .NET Core 2.1

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 null s, distribution, uniqueness, speed, … Of course one should, for solid code, also provide Equals override (and maybe also IEquatable<T> implementation).