Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why should I not write list.Count.Equals(0)

Tags:

c#

What would be your reason not to write

list.Count.Equals(0) 

when you probably write

list.Count == 0

Is there a technical/semantical reason?

like image 313
Elisabeth Avatar asked Dec 04 '25 06:12

Elisabeth


1 Answers

I think there is no difference between two statements for this specific case. Since you are checking the equality of int values; == operator and Equals do exactly the same operation.

But for some other cases, for example for the following case, they may return different values;

Double.NaN == Double.NaN // is false
Double.NaN.Equals(Double.NaN) // is true

Generally, for value types you may go with ==; but if it is a reference type, better to go with Equals.

For int the disassembly of a sample is displayed below; the generated assembly codes differ, so the performace is expected to differ;

            int a = 10;
00000080  mov         dword ptr [ebp-40h],0Ah 
                int b = 9;
00000087  mov         dword ptr [ebp-44h],9 

                bool x = a == b;
0000008e  mov         eax,dword ptr [ebp-40h] 
00000091  cmp         eax,dword ptr [ebp-44h] 
00000094  sete        al 
00000097  movzx       eax,al 
0000009a  mov         dword ptr [ebp-48h],eax 
                bool y = a.Equals(b);
0000009d  lea         ecx,[ebp-40h] 
000000a0  mov         edx,dword ptr [ebp-44h] 
000000a3  call        6B8803C0 
000000a8  mov         dword ptr [ebp-60h],eax 
000000ab  movzx       eax,byte ptr [ebp-60h] 
000000af  mov         dword ptr [ebp-4Ch],eax 
like image 137
daryal Avatar answered Dec 06 '25 22:12

daryal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!