Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Equals() == about number

Tags:

c#

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
like image 506
yu yang Jian Avatar asked Dec 13 '22 20:12

yu yang Jian


1 Answers

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;
}
like image 159
Giancarlo Melis Avatar answered Dec 28 '22 22:12

Giancarlo Melis