Lately I’ve been creating quite a few business entities with the ID of the object as the actual key to compare objects, which isn’t the default implementation. Because of that I had to override the Equals and the GetHashCode methods defined on the object class. Since copy/pasting code and editing parts of it for each new entity class isn’t the best way to develop an application, I created a small code snippet to make my life easier.
<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets
xmlns="http://schemas.microsoft.com/VisualStudio/2008/CodeSnippet">
<CodeSnippet Format="1.0.0">
<Header>
<Title>My .Equals() and .GetHasCode() snippet</Title>
<Shortcut>eq</Shortcut>
</Header>
<Snippet>
<!-- Add additional Snippet information here -->
<Declarations>
<Literal default="true" Editable="false">
<ID>ClassName</ID>
<ToolTip>Class name</ToolTip>
<Function>ClassName()</Function>
<Default>object</Default>
</Literal>
<Literal>
<ID>CompareItem</ID>
<ToolTip>Replace with the item on which objects are compared, mostly the ID.</ToolTip>
<Default>ID</Default>
</Literal>
</Declarations>
<Code Language="CSharp">
<![CDATA[/// <summary>
/// override object.Equals(obj);
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public override bool Equals(object obj) {
if (obj == null)
return false;
$ClassName$ entity = obj as $ClassName$;
if (entity == null)
return false;
return entity.$CompareItem$ == this.$CompareItem$;
}
/// <summary>
/// override object.GetHashCode();
/// </summary>
/// <returns></returns>
public override int GetHashCode() {
return $CompareItem$.GetHashCode();
}]]>
</Code>
</Snippet>
</CodeSnippet>
</CodeSnippets>