Compare two objects

Frits van Bommel fvbommel at REMwOVExCAPSs.nl
Tue Feb 10 05:43:35 PST 2009


Qian Xu wrote:
> Hi All,
> 
> I want to test, if two objects are equal. 
> The rules are as follows: 
> 1. When both are null, it should return true. 
> 2. When one of them is null, it should return false.
> 3. When both not null, then compare their values (as two strings)

((a is b) || (a && a == b))

Note that if a and b are both the same non-null object, opEquals will 
not be called; it'll just evaluate to true.


It's not very nice-looking, but it's the best you can do.
Of course, you could put it into a function:
-----
bool equals(T)(T a, T b) {
     return ((a is b) || (a && a == b));
}
-----

Note that this may behave strangely for empty arrays:
-----
char[] str;
equals(str, ""); // returns false
-----
But of course, that's what you asked for. 'str' is null and "" isn't...


More information about the Digitalmars-d-learn mailing list