Can C# 9.0 records support data structures like dictionaries and lists?

Viewed 2283

I've seen several examples of the new records feature in C# 9.0. I.e., being able to update individual properties to create new immutable records. What I'm curious to know is if the with syntax allows me to insert new entries into something like a dictionary, creating a new immutable dictionary along with all the sibling properties that make up the record.

For example, can I do something like this?

public record Person
{
    public string Name;
}
 
public record Car
{
    public string Model;
    public Dictionary<string, Person> Riders;
}

var car = new Car 
{
    Model = "Delorean",
    Riders = ("driver", new Person { Name = "Doc Brown" })
};

var newCar = car with
{ 
    Riders with ("passenger1", new Person { Name = "Marty McFly" })
};
1 Answers

As noted in this comment, for sure you can't do this because with works with record types only. But it's also not entirely clear what you mean anyway. The Dictionary<TKey, TValue> class isn't immutable to start with, so with doesn't seems necessary. What do you expect the proposed syntax above to do?

If you mean for it to replace the dictionary contents, you can do that with the current with syntax easily:

var newCar = car with
{
    Riders = new Dictionary<string, Person> { { "passenger1", new Person { Name = "Marty McFly" } } }
};

If you mean to add to the existing dictionary contents, but with a new instance, that's not quite as elegant, but is still easy and seems almost as nice to me:

var newCar2 = car with
{
    Riders = new Dictionary<string, Person>(car.Riders)
    {
        { "passenger1", new Person { Name = "Marty McFly" } }
    }
};

Are you hoping for something that avoids the new Dictionary... part? I do not believe that's possible in the current version of C#, even with all the enhancements that have been made over the past few versions to support collection initializers.

Related