0

Consider evaluation of following C# code under .net project with latest Json.NET nugget.

...

object x = Get();
var shouldEqual = x == "a"; //false

string x2 = Get();
var shouldEqual2 = x2 == "a"; //true

object x3 = Get();
var shouldEqual3 = x3.Equals("a"); //true

object x4 = "a";
var shouldEqual4 = x4 == "a"; //true

...

private class A
{
    public string X { get; set; }
}

private string Get()
{
    var des = JsonConvert.DeserializeObject<A>("{\"x\": \"a\"}");
    return des.X;
}

Could somebody clarify why would first condition produce negative comparison result.

Basically ran into problem under Xamarin's Android platform. After culpirit was extracted, retesting it in Console App produced same results.

Thanks in advance.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
Jurij
  • 1
  • 1
  • 3
    Rather than providing snippets, it would be easier to help if you'd produce a [mcve]. – Jon Skeet Apr 15 '16 at 20:52
  • 1
    Related: [Compare string and object in c#](https://stackoverflow.com/questions/21278322/compare-string-and-object-in-c-sharp) – dbc Apr 15 '16 at 20:53
  • Yup, it's basically a duplicate of that one. In the first case you're checking if the *references* are the same, and they're not. – Jon Skeet Apr 15 '16 at 20:53
  • You have to use equals() if you're comparing objects. If they're cast as strings, then you can use the == operator, as syntactical sugar, which uses equals() under the covers. – ManoDestra Apr 15 '16 at 20:55
  • Okay, thank you. I understand it now. It was actually my first thought, but last case confused me since I didn't know two string literals would create equal references. – Jurij Apr 15 '16 at 21:08

0 Answers0