Skip to content

Gendarme.Rules.Performance.OverrideValueTypeDefaultsRule(git)

Sebastien Pouliot edited this page Mar 2, 2011 · 1 revision

OverrideValueTypeDefaultsRule

Assembly: Gendarme.Rules.Performance
Version: git

Description

This rule checks all value types, except enumerations, to see if they use the default implementation of Equals(object) and GetHashCode() methods. While ValueType implementations work for any value type they do so at the expense of performance (the default implementation uses reflection to access fields). You can easily override both methods with much faster code since you know all meaningful fields inside your structure. At the same time you should also provide, if your language allows it, operator overloads for equality (op_Equality, == ) and inequality (op_Inequality, != ).

Examples

Bad example:

public struct Coord {
    int X, Y, Z;
}

Good example:

public struct Coord {
    int X, Y, Z;
    public override bool Equals (object obj)
    {
        if (obj == null) {
            return false;
        }
        Coord c = (Coord)obj;
        return ((X == c.X) && (Y == c.Y) && (Z == c.Z));
    }
    public override int GetHashCode ()
    {
        return X ^ Y ^ Z;
    }
    public static bool operator == (Coord left, Coord right)
    {
        return left.Equals (right);
    }
    public static bool operator != (Coord left, Coord right)
    {
        return !left.Equals (right);
    }
}

Notes

  • This rule is available since Gendarme 2.0

Source code

You can browse the latest source code of this rule on github.com

Clone this wiki locally