diegofrata / Generator.Equals

A source code generator for automatically implementing IEquatable<T> using only attributes.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Support for Record Struct

wainwrightmark opened this issue · comments

[Equatable]
public partial record struct MyStruct(int Data);

Generates

partial record MyStruct
{
    /// <inheritdoc/>
    [GeneratedCode("Generator.Equals", "1.0.0.0")]
    public bool Equals(MyStruct? other)
    {
        return
            base.Equals(other)
         && EqualityComparer<Int32>.Default.Equals(Data!, other.Data!)
            ;
    }
        
    /// <inheritdoc/>
    [GeneratedCode("Generator.Equals", "1.0.0.0")]
    public override int GetHashCode()
    {
        var hashCode = new HashCode();
            
        hashCode.Add(base.GetHashCode());
        hashCode.Add(
            Data!,
            EqualityComparer<Int32>.Default);
            
        return hashCode.ToHashCode();
    }
}

This is correct except it should say partial record struct MyStruct and the Equals method should be

/// <inheritdoc />
    [GeneratedCode("Generator.Equals", "1.0.0.0")]
    public bool Equals(MyStruct? other)
    {
        return
            other.HasValue
         && EqualityComparer<Int32>.Default.Equals(Data, other.Value.Data)
            ;
    }

also the GetHashCode method does not need to do hashCode.Add(base.GetHashCode());

I am willing to have a go at this myself.

I’m happy for you to have a go at it, however I’m not sure whether the current version of the Roslyn libraries being used support record structs! If we need to update them, then we will need to investigate what’s the impact — we might end up with either multi-targeting or a breaking change.

Let me know how you get along with it.

This is now available in 2.6.0