VS.NET Bug

One of my coworkers discovered the hard way today that in C# == is not the same as .Equals(). She had something like this:

object o1 = 1; object o2 = 1; Assert.IsTrue(o1 == o2);

This fails. The really nasty thing is that the Command Window and QuickWatch show that the expression evaluates to true!

So she changed it to:

object o1 = 1; object o2 = 1; Assert.IsTrue(o1.Equals(o2));

This succeeds! Why? From the docs:

For predefined value types, the equality operator (==) returns true if the values of its operands are equal, false otherwise. For reference types other than string, == returns true if its two operands refer to the same object. For the string type, == compares the values of the strings.

So that means strings are special, so the following should work:

object o1 = "1"; object o2 = "1"; Assert.IsTrue(o1 == o2);

And it does.

1 Comment

  • Ahh, you miss the underlying meaning of 1 in o1 = 1. When you tell a C++/javascript/php/perl/every other high-level language that a variable (o1) is 1, you are only telling the system that it's true, not that it actually equals 1. When you tell two variables that they are "true" this, in no way, means that o1 == o2. If you figure that when you tell a variable that it ="a string", you are only giving the string an alias. Two different aliases with the same string are equal, but those two aliases by themself are not equal.

Comments have been disabled for this content.