Object Equality

D

Doug Holland

Currently I am responsible for writing the C# coding standards document for
a client and I have been doing some investigations with ildasm to establish
some additional best practices.

When using either the C# equality operator '==' or the object.Equals()
methods, which is better?

Personally I prefer the object.Equals as it prevents accidental assignement
using only a single equals, however the C# '==' is certainly less to write
(not that that in itself justifies its use).

When you compile the code and examine the resultant IL using ildasm you see
that the C# '==' operator is not simply resolved to object.Equals ... as
such this begs the question, what is the difference between:

a == b

call bool [mscorlib /* 23000001 */]System.String/* 01000003
*/::blush:p_Equality(string, string) /* 0A000002 */

and:

string.Equals(a, b);

call bool [mscorlib/* 23000001 */]System.String/* 01000003
*/::Equals(string, string) /* 0A000003 */

Is there any performance difference between the two equality methods?

Or any other reason to prefer one over the other?

Thanks in advance

Doug Holland
 
T

Tian Min Huang

Hi Doug,

Thanks for your post. If you take a look at IL code of
String::blush:p_Equality:bool(string,string) as shown below, you will notice
that it just calls String::Equals. So, there is no much difference between
the two equality methods, and the code "a == b" is more readable for me.

.method public hidebysig specialname static
bool op_Equality(string a,
string b) cil managed
{
// Code size 8 (0x8)
.maxstack 8
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: call bool System.String::Equals(string,
string)
IL_0007: ret
} // end of method String::blush:p_Equality

Please feel free to let me know if you have any problems or concerns.

Have a nice day!

Regards,

HuangTM
Microsoft Online Partner Support
MCSE/MCSD

Get Secure! -- www.microsoft.com/security
This posting is provided "as is" with no warranties and confers no rights.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top