简体   繁体   中英

C# object equals int doesn't equal true

I have a very simple if statement but it always returns false never true. Here is my if statement

if (objectValue.Equals(intValue))
{
    return true;
}
return false;

Do I need to cast my objectValue variable to an int before comparing them?

Since Equals is a virtual method it will call the appropriate method of the subclass of object . In this case int.Equals . In a very simple example:

object o = 4;
int i = 4;

o.Equals(i) returns true . So your problem is somewhere else. Maybe objectValue is not an int , but a byte , short or other numerical type.

The problem isn't with having the int boxed in an object - that works just fine, as you can easily try yourself.

The problem only appears when the object doesn't actually contain an int , but rather a different numerical type, eg short or byte - in that case, you have to first unbox it to the correct type (for example, (short)objectValue ) and then do the comparison. Unboxing a boxed short to int results in InvalidCastException - you have to use the exact type with value-types.

Also, there's usually no need to use Equals for that - just do (int)objectValue == intValue or so.

int val;
if (int.TryParse(objectValue.ToString(), out val))
{
    if (val == intValue)
    {
        // return true;
    }
    else
    {
        //return false;
    }
}
else
{
    // value of obj is not int. you know here something is wrong
}

Using TryParse() method would be safer option even if you have non int value in the objectValue.

Yes you need to cast it

return ((int)objectValue).Equals(intValue);

without the cast a type comparison will be performed and object is never equal to an int, thats why you get the false value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM