opEquals

Returns true if lhs and rhs are equal.

bool
opEquals
(
const Object lhs
,
const Object rhs
)

Examples

If aliased to the same object or both null => equal

1 class F { int flag; this(int flag) { this.flag = flag; } }
2 
3 F f;
4 assert(f == f); // both null
5 f = new F(1);
6 assert(f == f); // both aliased to the same object

If either is null => non-equal

class F { int flag; this(int flag) { this.flag = flag; } }
F f;
assert(!(new F(0) == f));
assert(!(f == new F(0)));

If same exact type => one call to method opEquals

1 class F
2 {
3     int flag;
4 
5     this(int flag)
6     {
7         this.flag = flag;
8     }
9 
10     override bool opEquals(const Object o)
11     {
12         return flag == (cast(F) o).flag;
13     }
14 }
15 
16 F f;
17 assert(new F(0) == new F(0));
18 assert(!(new F(0) == new F(1)));

General case => symmetric calls to method opEquals

1 int fEquals, gEquals;
2 
3 class Base
4 {
5     int flag;
6     this(int flag)
7     {
8         this.flag = flag;
9     }
10 }
11 
12 class F : Base
13 {
14     this(int flag) { super(flag); }
15 
16     override bool opEquals(const Object o)
17     {
18         fEquals++;
19         return flag == (cast(Base) o).flag;
20     }
21 }
22 
23 class G : Base
24 {
25     this(int flag) { super(flag); }
26 
27     override bool opEquals(const Object o)
28     {
29         gEquals++;
30         return flag == (cast(Base) o).flag;
31     }
32 }
33 
34 assert(new F(1) == new G(1));
35 assert(fEquals == 1);
36 assert(gEquals == 1);
Suggestion Box / Bug Report