471,073 Members | 1,417 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 471,073 software developers and data experts.

Object Equality

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
*/::op_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
Jul 21 '05 #1
1 1376
Hi Doug,

Thanks for your post. If you take a look at IL code of
String::op_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::op_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.

Jul 21 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

1 post views Thread by Bijay Kumar | last post: by
reply views Thread by Bijay Kumar | last post: by
14 posts views Thread by serge calderara | last post: by
20 posts views Thread by nicolas.pourcelot | last post: by
16 posts views Thread by DamienS | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.