Home > Software engineering >  Changing property value in nested records
Changing property value in nested records

Time:10-06

Is it possible to use the with keyword to create a new instance of nested records with a different value for the nested property - both cases: simple property and collection? Let's see an example:

class Program
{
    static void Main(string[] args)
    {
        var company = new Company(
            Name: "Company1",
            Branch: new Branch(
                Location: "Krakow",
                Employees: new[]
                {
                    new Employee("Robert")
                }));

        Console.WriteLine(company);
    }
}

internal record Company(string Name, Branch Branch);
internal record Branch(string Location, IEnumerable<Employee> Employees);
internal record Employee(string FirstName);

In the above example I want to create a new record, but with changed values of the branch location ("Krakow") and employee name ("Robert"). How can I do this most effectively?

CodePudding user response:

You can nest your with expressions:

var clone = company with {
    Name = "Company2",
    Branch = company.Branch with {
        Location = "Warshaw",
        Employees = new[]
        {
            company.Branch.Employees.First() with 
            {
                FirstName = "Bob"
            }
        }}};

Console.WriteLine(clone);
foreach (var e in clone.Branch.Employees)
{
    Console.WriteLine(e);
}
  • Related