Search code examples
c#equality

.NET Delegate weird optimization


While browsing through the .NET Reference source I found the following piece of code, copied from https://referencesource.microsoft.com/#mscorlib/system/delegate.cs,196.

    public static Delegate Combine(Delegate a, Delegate b)
    {
        if ((Object)a == null) // cast to object for a more efficient test
            return b;

        return  a.CombineImpl(b);
    }

Notice the cast to (Object) which is weird. The reason this is done I'm assuming is not to use to use the == operator override of Delegate but the one from Object. However when browsing the code of Object I cannot find the definition of ==.

Question is then:

== on Object, where is it defined, what's it behavior?


Solution

  • From docs:

    For reference types other than string, == returns true if its two operands refer to the same object.

    // Reference equality: different objects, 
    // same boxed value: False.
    object s = 1;
    object t = 1;
    Console.WriteLine(s == t);