Consider this code:
int age = 25;
short newAge = 25;
Console.WriteLine(age == newAge); //true
Console.WriteLine(newAge.Equals(age)); //false
Console.ReadLin
Equals() is a method of System.Object Class
Syntax : Public virtual bool Equals()
Recommendation if we want to compare state of two objects then we should use Equals() method
as stated above answers == operators compare the values are same.
Please don't get confused with ReferenceEqual
Reference Equals()
Syntax : public static bool ReferenceEquals()
It determine whether the specified objects instance are of the same instance
== In Primitive
Console.WriteLine(age == newAge); // true
In primitive comparison == operator behave quite obvious, In C# there are many == operator overload available.
So in this case there is no implicit conversion from int
to short
but short
to int
is possible. So newAge is converted into int and comparison occurs which returns true as both holds same value. So it is equivalent to:
Console.WriteLine(age == (int)newAge); // true
.Equals() in Primitive
Console.WriteLine(newAge.Equals(age)); //false
Here we need to see what Equals() method is, we calling Equals with a short type variable. So there are three possibilities:
First type is not case here as number of arguments are different we calling with only one argument of type int. Third is also eliminated as mentioned above implicit conversion of int to short is not possible. So here Second type of Equals(object)
is called. The short.Equals(object)
is:
bool Equals(object z)
{
return z is short && (short)z == this;
}
So here condition got tested z is short
which is false as z is an int so it returns false.
Here is detailed article from Eric Lippert
For value types, .Equals
requires the two objects to be of the same type and have the same value, while ==
just tests if the two values are the same.
Object.Equals
http://msdn.microsoft.com/en-us/library/bsc2ak47(v=vs.110).aspx