microsoft / bond

Bond is a cross-platform framework for working with schematized data. It supports cross-language de/serialization and powerful generic mechanisms for efficiently manipulating data. Bond is broadly used at Microsoft in high scale services.
MIT License
2.61k stars 321 forks source link

[C#] Support for init properties on generated classes #1154

Open enioluwas opened 2 years ago

enioluwas commented 2 years ago

C# 9 introduced init properties that allow using object initializers to set readonly properties. This is quite useful for enforcing the copy-on-write pattern for immutable objects:

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

    public Person(Person copy)
    {
        this.FirstName = copy.FirstName;
        this.LasName = copy.LastName;
    }    
}

var johnDoe = new Person { FirstName = "John", LastName = "Doe" };
var janeDoe = new Person(johnDoe) { FirstName = "Jane" };

I see the Bond compiler CLI already has a --readonly-properties switch for making private set properties on generated classes, but that is too restrictive for this use case. Is it possible to add a new switch such as --init-properties to allow the above code sample on a Bond-generated class?

Related: https://github.com/microsoft/bond/issues/439

chwarr commented 2 years ago

Yes, this would be a welcome contribution.