adamjcooper.com/blog

Enterprise Software Development in C#


Snippets for Boilerplate Code When Overriding Equality and Hash Code

Overriding Equals and GetHashCode is easy, but implementing them correctly is not. As Jonathan Allen says in his excellent article A Detailed look at Overriding the Equality Operator, "It is surprisingly easy to make a mistake when overriding the equality operator. Not only does the equality operator bring along with it a lot of baggage, there is a lot of flawed guidance out there, even on the MSDN website. So we are going to try to clear the air by presenting a systematic breakdown of both a reference type and a value type that supports equality." Jonathan then goes on to provide guidance and code examples when overriding Equals or GetHashCode in a class or struct.

Using Jonathan's code examples as a starting point, I've created a couple of Visual Studio snippets, one for class and one for struct, to blast out all of the boilerplate code associated with overriding equality and hash code, allowing you to focus on implementing what's important.

Here's a 30-second demo to show you what it does:

Title

There are two snippets, one for class and one for struct, as outlined in Allen's original article. You can them here:

Equality and Hash Code Boilerplate Snippets for Class and Struct in C# (ZIP file)

Just unzip the file and use the Code Snippets Manager in Visual Studio to add these snippets to your environment (for Visual Studio 2008, click Tools... Code Snippets Manager... or Ctrl + K, Ctrl + B).

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Add comment


(Will show your Gravatar icon)  

  Country flag

biuquote
  • Comment
  • Preview
Loading





 
Powered by BlogEngine.NET 1.4.5.0 | Design by adamjcooper