How to best implement Equals for custom types?

前端 未结 10 709
春和景丽
春和景丽 2020-11-28 08:41

Say for a Point2 class, and the following Equals:

public override bool Equals ( object obj )

public bool Equals ( Point2 obj )

This is the

10条回答
  •  爱一瞬间的悲伤
    2020-11-28 09:07

    Using C# 7 and the is type varname pattern (https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/is#type), provides for a clean Equals(object) that deals with null and type checking using either of the below approaches:

    // using Equals(point)
    public override bool Equals(object obj) =>
        (obj is Point other) && this.Equals(other);
    
    // using the == operator
    public override bool Equals(object obj) =>
        (obj is Point other) && this == other;
    
    

    Obviously, you need to implement at least one of the following as well:

    public bool Equals(Point2 other);
    public static bool operator == (Point2 lhs, Point2 rhs);
    

提交回复
热议问题