0

In several projects now I have been writing a lot of boiler plate code in the form of equality and comparable implementations.
Resharper helps out a lot here, as it can auto-generate code where you select the fields that take part in the equality and then spits out boilerplate for you.

I was thinking since this code is quite predictable, yet still has lots of pitfalls, that it could maybe be lifted out of the classes themselves and ported to an attribute where you put an attribute above the fields that take part (maybe with an order number for equality).

Because "think before you code":

  • Why doesn't this already exist (or did my google skills fail me)
  • Why is this a bad idea?
Boris Callens
  • 90,659
  • 85
  • 207
  • 305

2 Answers2

2

Why doesn't this already exist

It does - in terms of IComparer<T> and IEqualityComparer<T>, in my MiscUtil project:

IComparer<Foo> comparer = ProjectionComparer<Foo>.Create(f => f.Name)
                                                 .ThenBy(f => f.Age);

And:

IEqualityComparer<Bar> eq = ProjectionEqualityComparer<Bar>.Create(b => b.Name);

Or:

IEqualityComparer<Bar> eq = ProjectionEqualityComparer<Bar>
    .Create(b => new { b.Name, b.Age });

I've been finding that more and more often I prefer to use those interfaces rather than IEquatable<T> and IComparable<T> as it's more flexible that way, and often there's no single natural way of ordering / comparing for equality.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
2

Sounds like your looking for AOP; essentially, clever attributes. There are several AOP frameworks available for .NET. These let you add arbitary logic to attributes, that you can then put on any class you want.

Community
  • 1
  • 1
thecoop
  • 45,220
  • 19
  • 132
  • 189
  • Good to see that I wasn't the first with this feeling. This puts a name on what I'm looking for. Got a whole slew of google threads now. Thanks :) – Boris Callens Feb 06 '13 at 10:26
  • After some looking into those frameworks, they might be what I'm looking for, but also are swatting a fly with a hammer – Boris Callens Feb 06 '13 at 10:37