Object Equality

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Doug Holland

    #1

    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(s tring, 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


  • Tian Min Huang

    #2
    RE: Object Equality

    Hi Doug,

    Thanks for your post. If you take a look at IL code of
    String::op_Equa lity:bool(strin g,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(str ing 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_Equa lity

    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.

    Comment

    Working...