Why doesn't == implementation call Equals for Guid?

3.6k views Asked by At

I've seen in the souce code of the GUID type in the .NET Framework that the implementation of Equals and the == operator execute very similar code.

Why doesn't the == operator call the Equals method on the firts argument? Something like this:

public static bool operator ==(Guid a, Guid b)
{ 
    return a.Equals(b);  
}
1

There are 1 answers

2
AudioBubble On BEST ANSWER

The comment is very telling:

public static bool operator ==(Guid a, Guid b)
{
    // Now compare each of the elements

This doesn't make sense by itself. Looking for that comment elsewhere in the file:

public bool Equals(Guid g)
{
    // Now compare each of the elements

but also

// Returns true if and only if the guid represented
//  by o is the same as this instance.
public override bool Equals(Object o)
{
    Guid g;
    // Check that o is a Guid first
    if(o == null || !(o is Guid))
        return false;
    else g = (Guid) o;

    // Now compare each of the elements

The comment only makes sense in that last method. This is a very strong indication that the Guid.Equals(Object) implementation came first.

It would be bad, or at least sub-optimal, if Guid.operator == and Guid.Equals(Guid) were implemented on top of Guid.Equals(Object), as that last method requires pointless allocations, and while it will hardly be noticeable in the common cases, there are certainly Guid comparisons that happen in some code in tight loops where the allocations would be measurable.

Now, it would certainly have been possible to make operator == use Equals(Guid), or vice versa, but it really isn't any additional work to copy and paste it twice instead of once.