Skip to content

Easy HashCode and Equals override #105

@RenanStigliani

Description

@RenanStigliani

Proposition

An easy way to implement default HashCode and Equals method, similar to that implemented by anonymous types

Situation

If the HashCode and Equals are already implemented by the language in some situation, why I should reimplement it?
I got myself, doing this more than one time:

    public class SomeThing
    {
        public decimal Tax { get; set; }
        public decimal Comission { get; set; }

        // Etc...

        public override int GetHashCode()
        {
            return new
            {
                Tax,
                Comission,
            }.GetHashCode();
        }

        public override bool Equals(object obj)
        {
            var other = obj as SomeThing;

            if (other == null)
                return false;

            return new { Tax, Comission }.Equals(new { other.Tax, other.Comission });
        }
    }

Why not something like this:

    [DefaultHashCode]
    [DefaultEquals]
    public class SomeThing
    {
        public decimal Tax { get; set; }
        public decimal Comission { get; set; }

        // Etc...
    }

Or maybe:

    public class SomeThing
    {
        public decimal Tax { get; set; }
        public decimal Comission { get; set; }

        // Etc...

        public override object GetStrucuralProperties()
        {
            return new { Tax, Comission };
        }
    }

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions