开发者

"bool" as object vs "string" as object testing equality

I am relatively new to C#, and I noticed something interesting today that I guess I have never noticed or perhaps I am missing something. Here is an NUnit test to give an example:

object boolean1 = false;
object booloan2 = false;
Assert.That(boolean1 == booloan2);

This unit test fails, but this one passes:

object string1 = "string";
object string2 = "string";
Assert.That(string1 == string2);

I'm not that surprised in and of itself that the first one fails seeing as boolean1, and boolean2 are different references. But it is troubling to me that the first one fails, and the second one passes. I read (on MSDN somewhere) that som开发者_Python百科e magic was done to the String class to facilitate this. I think my question really is why wasn't this behavior replicated in bool? As a note... if the boolean1 and 2 are declared as bool then there is no problem.

What is the reason for these differences or why it was implemented that way? Is there a situation where you would want to reference a bool object for anything except its value?


It's because the strings are in fact referring the same instance. Strings are interned, so that unique strings are reused. This means that in your code, the two string variables will refer to the same, interned string instance.

You can read some more about it here: Strings in .NET and C# (by Jon Skeet)

Update
Just for completeness; as Anthony points out string literals are interned, which can be showed with the following code:

object firstString = "string1";
object secondString = "string1";
Console.WriteLine(firstString == secondString); // prints True

int n = 1;
object firstString = "string" + n.ToString();
object secondString = "string" + n.ToString();
Console.WriteLine(firstString == secondString); // prints False


Operator Overloading.

The Boolean class does not have an overloaded == operator. The String class does.


As Fredrik said, you are doing a reference compare with the boolean comparison. The reason the string scenario works is because the == operator has been overloaded for strings to do a value compare. See the System.String page on MSDN.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜