Comparing expressions of type object

.net, c#, typechecking, types

Solution

`row["PersonID"]` is of type object, which means that != and == will use reference identity. Basically you're comparing boxed values.

If you use:

if (!object.Equals(row["PersonID"], tbxPersonID.EditValue))

then you'll get value equality semantics, and I suspect you'll be okay - assuming that tbxPersonID really is an `int`, either boxed or not.

Just to make things concrete, here's a short but complete example to show what I'm talking about:

using System;

class Test
{
    static void Main()
    {
        object first = 2;
        object second = 2;

        // Compares reference equality: false
        Console.WriteLine(first == second);

        // Compares value equality: true
        Console.WriteLine(object.Equals(first, second));
    }
}

Problem

Okay, this is probably very simple but, I have the below "checks" `(not at the same time)` and the First ALWAYS evaluates to TRUE while the Second SEEMS to work. This actually happens in each place that the row value is a number or bool`(Date seems fine...)`. If I walk through the code in Debug it shows the value of `row["PersonID"]` as 162434, the same as `tbxPersonID.EditValue`. Is this just a basic and beginner truth about programming that I missed in my `hodge-podge-self-education`? It seems, if I cast everything in question to a `string` first, I will be fine I would just like to know if I am correct and if there is a general rule as to what `Types` I would need to do this for? Doesn't Work ``` if (row["PersonID"] != tbxPersonID.EditValue) { row["PersonID"] = tbxPersonID.EditValue; } if (row["CitizenFlag"] != chkCitizen.EditValue) { row["CitizenFlag"] = chkCitizen.EditValue; _whatChanged.Add("CitizenFlag"); } ``` Works ``` if (row["PersonID"].ToString() != tbxPersonID.EditValue.ToString()) { row["PersonID"] = tbxPersonID.EditValue; } if (row["CitizenFlag"].ToString() != chkCitizen.EditValue.ToString()) { row["CitizenFlag"] = chkCitizen.EditValue; _whatChanged.Add("CitizenFlag"); } ```

Original source