Update* I am so sorry... my sample code contained an error which resulted in a lot of answers I didn\'t understand. In stead of
Console.WriteLin
Your code looks fine. The problem here is that StringBuilder has a confusing set of Equals that are contradictory. In particular, Equals(StringBuilder) disagrees with Equals(object), even when the object is a StringBuilder.
All that EqualityComparer
needs is a sane Equals(object) implementation. The interface (IEquatable
) is optional. Unfortunately StringBuilder doesn't have this (at least, by comparison to Equals(StringBuilder), which your third test is using).
But in general, the advice is: use EqualityComparer
; this supports: