C# snippet: override Object.Equals

Tags: .NET, C#, Snippet

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" ?>
    <CodeSnippet Format="1.0.0">
            <Title>My .Equals() and .GetHasCode() snippet</Title>
            <!-- Add additional Snippet information here -->

                <Literal default="true" Editable="false">
                    <ToolTip>Class name</ToolTip>
                    <ToolTip>Replace with the item on which objects are compared, mostly the ID.</ToolTip>
            <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();


comments powered by Disqus