Consider the following class:
internal class Test {
public int Code { get; set; }
public static bool operator ==(Test lhs, Test rhs) {
if (object.ReferenceEquals(lhs, rhs)) return true;
if (lhs == null || rhs == null) {
return false;
} else {
return lhs.Code == rhs.Code;
}
}
public static bool operator != (Test lhs, Test rhs) {
return !(lhs == rhs);
}
}
What is the outcome of the following test code, and why?
Test test1 = new Test { Code = 42 };
Test test2 = new Test { Code = 42 };
if (test1 != test2) {
Console.WriteLine("different");
} else {
Console.WriteLine("equals");
}
2 comments:
The ooutcome is Stack overflow, because this: if (lhs == null || rhs == null) creates a recursice loop that never ends.
That's correct Anders.
This should be a rather obvious one, but I've seen similar code enough to realize that it doesn't seem so.
And yes, these kinds of bugs should get caught in unittests ...
Post a Comment