Home > Software engineering >  How to refactor almost same two structs with different Equals?
How to refactor almost same two structs with different Equals?

Time:09-29

I have two almost the same two structs, only different implement Equals method
I don't want to use class but... I want to abstract equality.

Should I use the interface? I'd like your advice.

public readonly struct AStruct : IEquatable<AStruct>
{
    [Pure]
    public bool Equals(AStruct other) =>
        ... AStruct Equals implementation

    [Pure]
    public override bool Equals(object obj) =>
        obj is AStruct other && Equals(other);

    [Pure]
    public override int GetHashCode()
    {
        ...
    }

    ... other methods
}
public readonly struct BStruct : IEquatable<BStruct>
{
    [Pure]
    public bool Equals(BStruct other) =>
        ... BStruct Equals implementation

    [Pure]
    public override bool Equals(object obj) =>
        obj is BStruct other && Equals(other);

    [Pure]
    public override int GetHashCode()
    {
        ...
    }

    ... other methods
}

CodePudding user response:

If those structs are basically same, but you have them both to provide two ways to compare them, so different Equals implementations, i would suggest to use one struct but two IEqualityComparer<T>. Say this struct is now AB_Struct(one for both):

public class AB_Comparer_1 : IEqualityComparer<AB_Struct>
{
    public bool Equals(AB_Struct x, AB_Struct y)
    {
        // TODO...
    }

    public int GetHashCode(AB_Struct obj)
    {
        // TODO...
    }
}

public class AB_Comparer_2 : IEqualityComparer<AB_Struct>
{
    public bool Equals(AB_Struct x, AB_Struct y)
    {
        // TODO...
    }

    public int GetHashCode(AB_Struct obj)
    {
        // TODO...
    }
}

You can now use whatever comparer you need, for most compare or LINQ methods. For example:

if (items1.Intersect(items2, new AB_Comparer_1()).Any())
{ 
    // TODO ...
}

or as dictionary key comparer:

var dict = new Dictionary<AB_Struct, int>(new AB_Comparer_2());
  • Related