Search code examples
c#if-statementintegercomparisonchangetype

Comparing values after ChangeType not working


I have the problem, that comparing values after changing the type (in this case to int) does not work:

enter image description here

In my point of view (see the debugger), _pkValue and _defaultValue are both integers with the same value.

The problem is, that the if-statement should not be entered, because both values are 0.

I'm sure it is a very simple thing, but i can't figure it out.

EDIT: Code

object pkVal = pks.First().Value.GetValue(this, null);

if (pkVal != null)
{
    var defaultValue = TypeHelper.GetDefaultValue(pkVal.GetType());

    var _pkValue = Convert.ChangeType(pkVal, pkVal.GetType());
    var _defaultValue = Convert.ChangeType(defaultValue, pkVal.GetType());

    if (_pkValue != _defaultValue)
    {
        canset = false;
    }
}

SOLUTION

object pkVal = pks.First().Value.GetValue(this, null);

if (pkVal != null)
{
    var defaultValue = Simplic.TypeHelper.GetDefaultValue(pks.First().Value.PropertyType);

    if (!pkVal.Equals(defaultValue))
    {
        canset = false;
    }
}

Thank you!


Solution

  • Your problem is that _pkValue and _defaultValue aren't pure integers, they're boxed.

    The static type of the variables is object, which means that your != operator is checking for reference equality rather than comparing the boxed integer values.

    You can use the polymorphic Equals method to check for value equality:

    if (!_pkValue.Equals(_defaultValue))
    {
        canset = false;
    }