Reputation: 5897
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?
Upvotes: 0
Views: 2309
Reputation: 21
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.
Upvotes: 0
Reputation: 63732
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, e.g. 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.
Upvotes: 0
Reputation: 1904
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.
Upvotes: -1
Reputation: 354536
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.
Upvotes: 4