When I compare two variables typed as object and both contain same value,
the comparison result using == operator produces false.
object Var1 = "X";
object Var2 = "X";
// This produces false result
bool Match = Var1 == Var2;
Why is this happening?
Edit: Above is the code that actually works!
I have based it on my real code which looks
like this and does not work:
ChoiceValue = Choice.GetValue(FieldTemplate.ValueDataType);
if (ChoiceValue == Field.Value) RadioButton.IsChecked = true;
ChoiceValue is object and also the Field.Value is property typed as object.
Obviously works differently in different situations.
The reason this specific case returns false is because your strings are not interned. (String interning)
When I tested it, I got true, because my strings were interned.
In your case, this causes the object == operator to return false, since it compares by reference.
The reason your strings are not interned is because you are comparing dynamically built strings (meaning they were not known at compile time, but at runtime).
If you absolutely must use object variables, you can use
Equalsinstead of==, or you can manually intern strings withString.InternThis case is an anomaly of the reference-typed strings trying to behave like value types. This means that they compare by value, when using the string == operator. However, when you have objects, it uses the object == operator, which compares by reference.
This is explained in the documentation for string.