tags:

views:

165

answers:

1

Someone can explain me why this test fails :

        [TestMethod]
     public void WierdComparison()
     {
      var machineConf = ConfigurationManager.OpenMachineConfiguration();
      var systemWeb = machineConf.GetSectionGroup("system.web") as SystemWebSectionGroup;
      var prov = systemWeb.Membership.Providers.OfType<ProviderSettings>().Where((s) => s.Name == "AspNetSqlMembershipProvider").First();

      bool result, expected;
      var connectionStringName = prov.ElementInformation.Properties["connectionStringName"].Value;


      result = connectionStringName.Equals("LocalSqlServer");
      expected = true;

      Assert.AreEqual(expected, result);

      result = connectionStringName == "LocalSqlServer";
      expected = true;

      Assert.AreEqual(expected, result); //This assertion fails
     }
+7  A: 

That is because you are comparing an Object to a String.

If you compare two strings, the == operator is overloaded to compare the values of the strings. If you compare an object and a string, the == operator that compares two Object references is used, and that simply compares the references, not the values.

The Equals method is a virtual method, so eventhough you call it on an Object reference, it will still use the overridden method in the String class as the actual type of the object is String.

Guffa
30 seconds too late :)
Sam Saffron
Thanks ;) tricky "bug" to find.
Nicolas Dorier
This is why you should NEVER use the == operator to compare strings. Use String.Compare(), which also lets you use an appropriate culture and do case-insensitive comparisons.
Jon Grant
@Jon: You are barking up the wrong tree here, even if it's your favourite tree. ;) The problem here is the use of "var" to declare variables so that you don't clearly see the actual type. Using the == operator works fine as long as you compare string references.
Guffa