How would you implement this With
method? Let's make a try:
public Person With(string firstName = null, string lastName = null,
string[] phoneNumbers = null)
{
return new (
firstName ?? this.FirstName,
lastName ?? this.LastName,
phoneNumbers ?? this.PhoneNumbers
);
}
The problem with this approach is that we are not able to set a field to null as in
Person person2 = person1 with { phoneNumbers = null };
Therefore another approach is required. We could add overloads of every possible parameter combination
public Person With(string firstName);
public Person With(string lastName);
public Person With(string[] phoneNumbers);
public Person With(string firstName, string lastName);
public Person With(string firstName, string[] phoneNumbers);
public Person With(string lastName, string[] phoneNumbers);
public Person With(string firstName, string lastName, string[] phoneNumbers);
The problem is that the number of required overloads grows exponentially with the number of parameters:
2n - 1.
Yet another approach would be to let the compiler handle a call like person1.With(FirstName:"John")
. It would be syntactic sugar for compiler generated code. This introduces other problems:
- It does not behave as we would expect from other methods.
- How would Intellisense display the parameters of this pseudo method? As in our first attempt? This would be misleading because of this nulling problem.
- It could conflict with a user defined method of the same name.
Some interesting links relating to the implementation of Non-destructive mutation (with
keyword):