Back to basics – object equality

What do you think this piece of code will output?

    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(GetValue() == (object)true);
            Console.WriteLine(object.Equals(GetValue(), true));
        }

        static object GetValue()
        {
            return true;
        }
    }

I won’t be like others and ask you not to run the code. Run the code if you feel like it. I’ll wait here.

Back already? Surprised?
I surely have been.. I’ve found a piece of code similar to this as I was cleaning up code in our repository. You have a method that is required to return object (as in System.Object) and you want to check if, unboxed, it holds the value of true (or not).

Why exactly does

    GetValue() == (object)true

return false considering that GetValue() returns always a true value? Well… because you are comparing two instances of a System.Object and the ‘==’ operator is coded in a way that uses the ReferenceEquals (and not Equals) method on System.Object.

The author could have unboxed it to a local variable and do the check after but the speed of coding is so much important for some of us.. Thank you ReSharper for pointing this to us and fixing a potentially subtle bug.

Leave a Comment


NOTE - You can use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

This site uses Akismet to reduce spam. Learn how your comment data is processed.