Let's make our anonymous objects easier to copy using the with
expression!
Current Implementation
Introduced in C# 9.0, the with
keyword was designed to create record
objects from other record
objects in a non-destructive manner; that is, create a copy of a record
and change one or more properties.
public record Animal (string Name, string Type, int Age);
var dog = new Animal("Charlie", "Dog", 7);
var cat = dog with { Type = "Cat" };
Console.WriteLine(cat.Name); //Charlie
However, we could not do this with anonymous objects. Imagine we have the following:
var dog = new { Name = "Max", Type = "Dog", Age = 10 };
Now imagine we want to create a new anonymous object, with the same properties, using the existing one as a template. We would need to do this in a roundabout fashion:
var cat = new { dog.Name, Type = "Cat", dog.Age };
New Implementation
In C# 10, we can now use the with
keyword to create the new anonymous object from the old one, in a more concise way:
var dog = new { Name = "Max", Type = "Dog", Age = 10 };
var cat = dog with { Type = "Cat" };
In essence, the with
keyword now functions in the same manner on both record
objects and anonymous objects.
Demo Project
Although it won't compile (as of publishing time), I have included a sample of how this feature might work in the demo project for this series:
Happy Coding!