Hi,
Whats best? To use or not to use Equals();
Cheers !Code:int a = 2;
int b = 3;
if(a != b)
{
//Sth
}
or
if(!a.Equals(b))
{
//Sth
}
Printable View
Hi,
Whats best? To use or not to use Equals();
Cheers !Code:int a = 2;
int b = 3;
if(a != b)
{
//Sth
}
or
if(!a.Equals(b))
{
//Sth
}
I am not sure what differences they would have at machine code level. But there really is no big deal for something so small. In the case of something so simple i would usually go for which is easiest to understand ;)
In the case of value types, such as integers, there is no functional difference between the two; however, the Equals method will cause one of the two to be boxed into a reference type, and is thus less efficient than using the != or == operators.
In the case of reference types, the != and == operators perform an identity comparison (i.e. whether or not the references point to the same object). The Equals method attempts to perform a value comparison (i.e. whether or not the references point to objects that both represent the same data [and may or may not be the same object]).
Classes usually provide their own implementation of the Equals method in order to facilitate correct value comparisons between instances of their type.