Open lanwin opened 8 years ago
Hello lanwin,
Unfortunately, I did not found a silver bullet to get immutability without boilerplate in C# 6. But I can tell you what we do and where we want to go with immutability at my job.
public class Customer
{
public string FirstName { get; private set; }
public string LastName { get; private set; }
public ImmutableList<Address> Addresses { get; private set; }
public Customer()
{
}
public Customer(Customer other)
{
this.FirstName = other.FirstName;
this.LastName = other.LastName;
this.Addresses = other.Addresses;
}
public Customer WithFirstName(string firstName)
{
return new Customer(this) { FirstName = firstName };
}
public Customer WithLastName(string lastName)
{
return new Customer(this) { LastName = lastName };
}
public Customer WithAddresses(ImmutableList<Address> addresses)
{
return new Customer(this) { Addresses = addresses };
}
}
If those tips help you, I will update the readme in the few next days.
Maybe you will find the last C# 7 design notes interesting.
The new C# records could be useful to build an immutable state without boilerplate !
For anyone who is interested I made something to minimize the boilerplate needed when using redux (at least while C# doesn't implement it itself):
https://github.com/xaviergonz/T4Immutable T4Immutable is a T4 template for C# .NET apps that generates code for immutable classes.
As an extra note I just updated it to properly support properties that are collections. GetHashCode, Equals, etc will work OK as long as the collections are equivalent.
So far so good. But how would you create and mutate the immutable state in C# without creating a lot of mess and boilerplate?
A few suggestions in the readme would be fantastic.