Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

C# Record with Expression: Copy and Modify Records

Learn how to use C# with expressions to create modified copies of immutable records, with practical examples and limitations.

~4 min readC#
#C##Records#Immutability#With Expression
Diagram showing a C# record being copied with a with expression to create a modified instance

Why Records Need the with Expression

Records in C# are designed for immutable data. For positional records, the generated properties are init-only, so you cannot modify an existing instance after initialization. To change a property, you must create a new instance. The C# with expression is the language feature that makes this concise and type-safe.

Consider this record:

csharp
public record Person(string FirstName, string LastName, int Age);

If you want a new Person with a different Age, you cannot do person.Age = 30; because the property is init-only. Instead, you write:

csharp
var person = new Person("Jane", "Doe", 28); var olderPerson = person with { Age = 29 };

The with expression creates a shallow copy of person, then applies the specified property changes. The result is a new Person instance with FirstName and LastName copied from the original and Age set to 29.

Syntax and Basic Usage

The with expression syntax is straightforward: original with { Property1 = value1, Property2 = value2 }. You can change any number of properties, including none (which still creates a copy). The expression works on both positional records and records with explicit properties.

csharp
public record Point(int X, int Y); var p1 = new Point(1, 2); var p2 = p1 with { Y = 3 }; // X remains 1

For records with init-only properties, the with expression is the only way to "modify" them without reflection. It respects access modifiers: you can only assign properties that are accessible from the current scope.

How the with Expression Works Under the Hood

When you define a record class, the compiler generates a protected copy constructor that takes an existing record and copies all its fields. The with expression calls this copy constructor and then assigns the specified properties. This is not reflection; it compiles to direct code, making it fast and type-safe.

For record structs (introduced in C# 10), the with expression copies the struct value and then applies the specified changes. This value copy avoids a separate heap allocation, which can be cheaper for small data.

This copy constructor can be customized for record classes. If you define your own copy constructor, the with expression will use it. This allows you to control what gets copied, for example, to perform a deep copy of certain fields.

Using the with Expression with Inheritance

Record classes support inheritance; record structs do not. When you use a with expression on a derived record instance, the result is the same runtime type as the original. The compiler emits a virtual clone member to handle this polymorphically.

csharp
public record Base(int Id); public record Derived(int Id, string Name) : Base(Id); var derived = new Derived(1, "Test"); var modified = derived with { Name = "Changed" }; Console.WriteLine(modified.GetType()); // Derived

The with expression preserves the actual type, so you do not lose derived properties.

Practical Example: Updating Nested Records

When records contain other records, the with expression performs a shallow copy. The top-level record is new, but nested reference types are shared between the original and the copy.

csharp
public record Address(string Street, string City); public record Employee(string Name, Address Address); var employee = new Employee("Alice", new Address("123 Main", "Springfield")); var relocated = employee with { Address = new Address("456 Oak", "Shelbyville") };

Here, relocated has a new Address instance, but if you only change a property of the nested Address, you need to create a new Address first:

csharp
var updated = employee with { Address = employee.Address with { City = "Metropolis" } };

This is because the with expression does not recursively copy nested objects.

Performance and Allocation Considerations

The with expression allocates a new instance. For reference-type records, this is a heap allocation; for record structs, the copy is a value copy. If you create many modified copies in a hot path, consider the allocation overhead. In most application code, this is negligible, but for large records or frequent operations, you might want to measure.

One subtle point: the with expression does not modify the original instance. It creates a new object, and the listed properties are assigned on that new object through their normal setter or init accessor. Validation in those accessors runs on the new object. If you need validation during the copy itself, define a custom copy constructor or use a factory method.

with Expression vs Manual Copying

Manual copying involves creating a new instance and assigning all properties. For records with many properties, this is verbose and error-prone. The with expression is more concise and avoids the risk of missing a property.

ApproachProsCons
with expressionConcise, type-safe, preserves runtime typeShallow copy by default; custom copy logic requires extra code
Manual copyFull control, can apply validationVerbose, easy to miss properties

Use the with expression when you need a simple modified copy. Use manual copying or a factory method when you need to apply complex transformation rules or validation.

Limitations and Edge Cases

  • The with expression is available on records and record structs. In C# 10 and later, it can also be used on ordinary structs. It is not available on ordinary classes that are not records.
  • It performs a shallow copy. Nested mutable objects are shared.
  • If a record has a property with no accessible setter or init accessor, such as a get-only property, the with expression cannot change it.
  • When using inheritance, the with expression preserves the runtime type, but you may need to account for a derived record's custom copy constructor behavior.

Understanding these limitations helps you decide when to use the with expression and when to implement a custom cloning strategy.

Try matching browser tools

All tools

Small utilities that fit C# work — they run entirely in this browser tab, so nothing you paste leaves your device.

All C# guides

More in C#

All C# guides

The guides filed next to this one in C#, in library order.