When we box two value types(which are different types but compatible to compare the values eg: int and short) and try to call Equals method on that gives false even the values are same.
Case 1:
int a = 5;
short b = 5;
var ob_a = (object) a;
var ob_b = (object) b;
var result = a == b; // true
var result_for_objects = ob_a.Equals(ob_b); // false
On the other hand when the both value types are same the Equals returns the actual value comparison result.
Case 2:
int a = 5;
int b = 5;
var ob_a = (object) a;
var ob_b = (object) b;
var result = a == b; // true
var result_for_objects = ob_a.Equals(ob_b); // true
I compared the both disassembly code for of both case but it was same, I was not able to find any difference.
var result = a == b;
012404DE mov eax,dword ptr [ebp-40h]
012404E1 cmp eax,dword ptr [ebp-44h]
012404E4 sete al
012404E7 movzx eax,al
012404EA mov dword ptr [ebp-50h],eax
var result_for_objects = ob_a.Equals(ob_b);
012404ED mov ecx,dword ptr [ebp-48h]
012404F0 mov edx,dword ptr [ebp-4Ch]
012404F3 mov eax,dword ptr [ecx]
012404F5 mov eax,dword ptr [eax+28h]
012404F8 call dword ptr [eax+4]
012404FB mov dword ptr [ebp-5Ch],eax
012404FE movzx eax,byte ptr [ebp-5Ch]
01240502 mov dword ptr [ebp-54h],eax
- If value types inside the boxed objects are not same which Equals method is actually getting called?
- When both value types inside the boxed objects are same how is it calling Equals method of that value type?