OdeToCode IC Logo

Comparing Strings in NUnit 2.2 versus NUnit 2.4

Monday, May 7, 2007

John and I were trying to figure out why a test wasn't failing on his machine. We finally realized different versions of NUnit were producing different results.

In nUnit 2.2, Assert.AreEqual(string, string) ultimately calls String.Equals to perform the string comparison.

In nUnit 2.4, Assert.AreEqual(string, string) ultimately calls String.Compare to perform the string comparison.

As the following code will demonstrate, these methods can behave differently.

class Program
static void Main()
string s1 = new string(new char[] { 'a', 'b', 'c' });
string s2 = new string(new char[] { 'a', 'b', 'c', (char)0} );

bool result1 = s1.Equals(s2);
bool result2 = String.Compare(s1, s2) == 0;

Debug.Assert(result1 == result2); // this explodes

String.Equals performs an ordinal comparison that operates on the individual numeric Char values inside each string. String.Compare performs a linguistic comparison that operates on the value of the string as a whole, and takes into account culture-specific casing, sorting, formatting, and parsing rules. See "New Recommendations for Using Strings in Microsoft .NET 2.0" by Dave Fetterman for a detailed discussion.