bool as object vs string as object testing equality

Posted by Ray Pendergraph on Stack Overflow See other posts from Stack Overflow or by Ray Pendergraph
Published on 2010-04-16T18:01:15Z Indexed on 2010/04/16 18:03 UTC
Read the original article Hit count: 225

Filed under:
|
|

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.

Does anyone know the reason for these differences or why it was implemented that way? Can anyone think of a situation where you would want to reference a bool object for anything except its value?

© Stack Overflow or respective owner

Related posts about c#

Related posts about .NET