amis92 / RecordGenerator

C# immutable records generator
https://amis92.github.io/RecordGenerator/
MIT License
72 stars 10 forks source link

Generate classes from readonly fields #103

Closed bboyle1234 closed 5 years ago

bboyle1234 commented 5 years ago

Sometimes an immutable class should have readonly fields that are not exposed by a getter property. This allows a lot more flexibility and advanced usage.

// The class
[Record(Features.Default | Features.GenerateGetterProperties)]
public sealed partial class SomeObject { 
  private readonly int property1;
  [SuppressGetter] private readonly int property2;
}

// Example code gen
partial class SomeObject { 
  public int Property1 => property1;
  public SomeObject(int property1, int property2) { 
    this.property1 = property1;
    this.property2 = property2;
  }
}
amis92 commented 5 years ago

That's more of a primary constructor feature (https://github.com/dotnet/csharplang/issues/2691). Here we focus on records - always being a public, ordered list of immutable properties. There are variants to be considered (like dataset, which would be an unordered bag of properties), but hiding a ctor parameter doesn't fit in, I think.

bboyle1234 commented 5 years ago

ok. Thanks for considering. As I commented earlier, the reason for suggesting is the hope of using this library not only to build records, but to build what we really want ... powerful, flexible immutable classes with customizable memberwise equality. Sometimes this flexibility requires that the immutable class be built from fields instead of public readonly properties. AArnott demonstrates this well in his ImmutableObjectGraph project. When I first saw the "build from readonly fields" method used there, I didn't like it. Then I thought it over for a few days and see many good reasons to go that way.