Skip to content

[Feature] specify EqualityComparer #119

Open
@ndrwrbgs

Description

Preamble

  • Fody 6.0.0
  • Equals.Fody 4.0.0
  • MSBuild 16

Describe the issue

When comparing things like string, often you need to specify the IEqualityComparer to use for the comparison. I'd like to see(/add, it's important enough to me that Equality not be so much boilerplate in projects) the ability to specify the EqualityComparer for a field/property to be used by the generated code.

Minimal Repro/Sample

There are a couple different possibilities given in the below.

[Equals]
class TypeUnderTest : IEquatable<TypeUnderTest>
{
  private static readonly IEqualityComparer<String> NameComparer = StringComparer.OrdinalIgnoreCase;
  
  public int Number { get; private set; }
  
  [EqualityComparer(fromLocalProperty: nameof(NameComparer))]
  // Other examples:
  //[EqualityComparer(fromExternalProperty: "System.StringComparer.OrdinalIgnoreCase" /* not sure if I like this, since it'd need to know the assemblies to load */)]
  //[EqualityComparer(typeof(MyCustomStringComparer /* must have new() */)]
  //[EqualityComparerFactory(fromLocalMethod: nameof(CreateNameComparer))]
  public string Name { get; }

  bool IEquatable<TypeUnderTest>.Equals(TypeUnderTest other) => throw new ShouldBeReplacedByFodyEqualsException("Auto-implemented");
  
  private static IEqualityComparer<string> CreateNameComparer() => StringComparer.OrdinalIgnoreCase;
}

I like the fromExternalProperty the most -- since it reduces the code impact to literally 1 line to specify 1 thing (oh, how code should be!) but since I'm concerned about the making sure we pull in the right dependencies and prefer for usage errors to be caught by the compiler, I think that I officially back this approach (unless a maintainer of the project would feel versed enough in this stuff to validate a PR I send is correct/incorrect).

[Equals]
class TypeUnderTest : IEquatable<TypeUnderTest>
{
  private static readonly IEqualityComparer<String> NameComparer = StringComparer.OrdinalIgnoreCase;
  
  public int Number { get; private set; }
  
  [EqualityComparer(fromLocalProperty: nameof(NameComparer))]
  public string Name { get; }

  bool IEquatable<TypeUnderTest>.Equals(TypeUnderTest other) => throw new ShouldBeReplacedByFodyEqualsException("Auto-implemented");
}

Make an effort to fix the bug

Will be doing, but generally want to know that a proposal will be entertained before doing the work -- but important enough to me that I would fork the library if not :)

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions