Different code generated

hey codemonkey! thanks for the great course! I am learning a lot! So i was writing the code for the struct when i did what you said and allowed Visual Studio to generate the rest of the code for me… here is what it wrote…
image
it is different from what the video shows…(on the “Equals” and “GetHashCode”) is that a Visual Studio update causing that or what? Thanks!

The code shown in the video is actually after Hugo replaced the default contents (what you got) with the new contents that determine the equality. Clever editing to save time. [Edit: This was not the case. It turns out that different versions of Code can give different default implementations]

When auto generating a virtual method that has a default implementation, the compiler will always give a default content of

return base.[functionname](parameters);

Which is effectively “Just return what we would have returned if we never overrode it”.

Newer versions of Visual Studio (at least) will generate actual implementations
image
Which produces

    public override bool Equals(object obj)
    {
        return obj is GridPosition position &&
               X == position.X &&
               Z == position.Z;
    }

    public override int GetHashCode()
    {
        return HashCode.Combine(X, Z);
    }

but I believe that depends on a few things because the HashCode object didn’t exist until recently. And I suppose you have to choose the menu option, as opposed to just overriding the functions

Good to know… it may be a matter of version (and compiler).

I did a few tests on JetBrains Rider…
If I chose Implement Missing Members, I actually got

public bool Equals(object other)
{
    throw NotImplementedException();
}

If I chose Generate Equality Members, then I got

    public bool Equals(GridPosition other)
    {
        return x == other.x && z == other.z;
    }

    public override bool Equals(object obj)
    {
        return obj is GridPosition other && Equals(other);
    }

    public override int GetHashCode()
    {
        return HashCode.Combine(x, z);
    }

I haven’t tested these settings in either Visual Studio app (code or Community)

thanks for the responses! i am not sure why he made the changes though… the code works perfectly without it… just with the default…

I didn’t cut the video in that part, what you see is what my Visual Studio generated. Maybe different VS versions generate different things? Did you make sure to define the GridPosition as a Struct and not a Class?

hmm… yeah, it is a struct… weird. Thanks for the great course btw!

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Yeah, I got different results between different editors for this.

Privacy & Terms