“bool” as object vs “string” as object testing equ

2019-05-27 11:23发布

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 some 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?

标签: c# .net mono nunit
3条回答
你好瞎i
2楼-- · 2019-05-27 11:46

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.

查看更多
太酷不给撩
3楼-- · 2019-05-27 11:49

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
查看更多
狗以群分
4楼-- · 2019-05-27 11:57

Operator Overloading.

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

查看更多
登录 后发表回答