ReferenceEquals and the Equality Operator

3 posts, 1 answers
  1. Joni
    Joni avatar
    12 posts
    Member since:
    Aug 2011

    Posted 10 Aug 2011 Link to this post


    Love the product! I have a question (which would also have been relevant for Reflector).

    I was curious to see what went down when the ReferenceEquals method of the Object class was called. See the screenshot below.

    Is there a way to drill into the == operator?
    Is there a place where that is reflected?
    Does this mean that using == is more efficient that using ReferenceEquals?

  2. Answer
    Nikolay G Rusev
    Nikolay G Rusev avatar
    44 posts

    Posted 11 Aug 2011 Link to this post

    Hello Joni,

    Thank you for the kind words. Now let me answer your feedback.

    By inspecting the IL code of the ReferenceEquals method you can see that the == operator is compiled to a simple IL instruction that compares two values. Since the values of the arguments are references then all it does is checking if the two references are equal. The == operator is compiled to the same instruction for every reference type that does not override it.

    You can always cast the two operands to object and check reference equality with == instead of ReferenceEquals. I don't think that the difference in performance will be significant so choosing which one to use is a matter of personal preference.

    I hope this answers your questions. And if you have more, we'd love to hear again from you.

    Nikolay G Rusev
    the Telerik team

    Explore the entire Telerik portfolio by downloading the Ultimate Collection trial package. Get now >>

  3. Joni
    Joni avatar
    12 posts
    Member since:
    Aug 2011

    Posted 11 Aug 2011 Link to this post

    Thanks Nikolay!

    I have seen people using ReferenceEquals, or even just Object.Equals(null, someObject), instead of something like if(someObject == null).

    I figured there must be a performance improvement or something, as the syntax is more verbose than a simple == operator.

    Once again, it seems that the good old proven way of doing things is the best.

Back to Top