Is there anything similar to Java AutoValue in C#?

331 views Asked by At

After working on a Java project for some time then coming back to C#, I've found myself really missing AutoValue. Specifically, I'd like the ability to:

  • Produce an immutable value class with minimal boilerplate.
  • Have things like equality and hash code automatically handled for me.
  • Ideally, have it automatically generate a builder to allow fluent construction and arbitrary validation like "if you give parameter A, you must also give B".
  • In the same vein, a toBuilder()-style function to make a deep copy of an existing instance while making some modifications.

All of that would have been really easy with AutoValue. Is there anything similar? I could, of course, implement all that functionality myself, but it's a lot of boilerplate, making it harder to maintain and more error-prone.

1

There are 1 answers

1
StuartLC On BEST ANSWER

From what you've described, it seems that you will need to wait until C#9 record types in order to get what you've described of java's AutoValues, i.e. in C#9, you should be able to declare:

public data class Person
{
    public string FirstName { get; init; }
    public string LastName { get; init; }
}

You'll then get:

In the interim (C#8 and prior), you'll need to do some of this by hand, i.e.

As an aside, if you have just switched from Java to C#, you may not be aware of structs as value types for trivial 'records', which from the docs:

Structs are best suited for very small data structures that contain primarily data that is not intended to be modified after the struct is created.

Although structs do have a default implementation of value equality, this can be unacceptable given that it is just the first field included in the hashcode, and that you'd need to provide an implementation of operator == if you want to use == for value equality.

That said, the use cases for structs must be carefully considered, and should generally be used only for trivial immutable records or for performance reasons when used in arrays.