-1

I have the following code in order to compare a value read from a DB with some expected values:

object o = row.get_Value(fieldIndex);
bool equal = o == "mytext";

When I debug that o has the value "mytext". However the comparison yields false. If on the other hand I cast o to string, the comparison works:

bool equal = (string)o == "mytext";

While row is a COM-object, o.GetType() returns string.

Unfortunately I cannot provide what get_Value does, as I don´t have its sourcecode.

So why does the second comparison work while the first one does not?

MakePeaceGreatAgain
  • 35,491
  • 6
  • 60
  • 111
  • My guess is that the type of `o` is just a reference type of some description that has an implicit string cast. – Liam Dec 01 '20 at 12:18
  • *"So why does the second return true?"* - I am confused, you are casting something to string (which produces `"mytext"`) and asking why `"mytext" == "mytext"` is `true`? – Sinatr Dec 01 '20 at 12:23
  • 3
    `string` overloads the `==` operator. This overload is called in your second snippet, but not your first. – Klaus Gütter Dec 01 '20 at 12:24
  • @Sinatr to cleariffy: `"mytext"` is interned, so comparing it to `"mytext"` of course returns true. So I´m wondering why it is intered in the second but not in the first case? – MakePeaceGreatAgain Dec 01 '20 at 12:25
  • @KlausGütter Yeap, that sounds plausible. – MakePeaceGreatAgain Dec 01 '20 at 12:29

1 Answers1

1

The minimal reproducible example would be

object o = "mymy";
string s = "my";
Console.WriteLine(o == s+s);

This gives you the compiler warning CS0252, which basically says that you get the equality comparison of object and not the equality comparison of string.

string changes the meaning of == to that of .Equals(), which tests for character by character equality.

Thomas Weller
  • 55,411
  • 20
  • 125
  • 222