I try following code use ==
and Equals
on number comparison:
Console.WriteLine( (int)2 == (double)2.0 );
Console.WriteLine( ( (int)2 ).Equals( (double)2.0) );
Console.WriteLine((float)2.0 == (double)2.0);
Console.WriteLine( ( (float)2.0 ).Equals( (double)2.0 ) );
The result:
true
false
true
false
int, double, float
are all ValueType
, after reading posts Here1 and Here2, I still cannot understand why ==
and Equals
turns out different result,
What is the working detail behind ==
and Equals
in these 4 cases about number?
(if this question is duplicate please tell me)
EDIT: 4 more interesting cases:
double, float <-> int
Console.WriteLine((double)2.0 == (int)2); //True
Console.WriteLine(((double)2.0).Equals((int)2)); //True
Console.WriteLine((float)2.0 == (int)2.0); //True
Console.WriteLine(((float)2.0).Equals((int)2.0)); //True
double, int <-> float
Console.WriteLine((double)2.0 == (float)2.0); //True
Console.WriteLine(((double)2.0).Equals((float)2.0)); //True
Console.WriteLine((int)2 == (float)2.0); //True
Console.WriteLine(((int)2).Equals((float)2.0)); //False
From MSDN:
ValueType.Equals indicates whether this instance and a specified object are equal.
and
Return value:
Type: System.Boolean
true if obj and this instance are the same type and represent the same value; otherwise, false.*
If you do this:
int a = 1;
double b = a;
bool check = a.Equals(b);
You are calling this implementation of Equals:
[__DynamicallyInvokable]
public override bool Equals(object obj)
{
if (!(obj is int))
return false;
return this == (int) obj;
}
If you do this:
int a = 1;
int b = a;
bool check = a.Equals(b);
You are calling this other:
[NonVersionable]
[__DynamicallyInvokable]
public bool Equals(int obj)
{
return this == obj;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With