Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access the original value of a record in a with expression

Tags:

c#

c#-9.0

Given a record

public record Address(string Name);

How can I access the original value of a property in a with expression? What I would like to do is something like:

var address = new Address("foo");
var extendedAddress = address with { Name = $"{Name} - bar" }; // does not compile

so that extendedAddress == "foo - bar".

Is there a way of referencing the original record that is being overridden so that the values can be "extended"?

TO BE MORE SPECIFIC

The example I gave is misleading since one could simply do:

var extendedAddress = address with { Name = $"{address.Name} - bar" };

But what I'm looking for is to achieve this within a single expression. Something like:

customers.Select(x => x.GetAddress() with Name = $"{Name} - bar")
like image 344
Dejan Avatar asked Nov 02 '25 21:11

Dejan


1 Answers

There's nothing automatic here, for good reason: Name already has resolution rules (an instance member this.Name, a static Name, a type called Name, etc). Just use address.Name from a local, perhaps via a let expression in LINQ

like image 168
Marc Gravell Avatar answered Nov 05 '25 13:11

Marc Gravell