C
C#10mo ago
bacon

❔ Custom Copy Semantics for `record struct`?

Hey all - I'm having a hard time figuring out how to (and if it's even supportedt) to do custom copy semantics for record structs. Changing my record type to a record/record class properly calls the copy ctor, but if it's a record struct, when I use with the copy ctor isn't being called. Would love any help here
8 Replies
Thinker
Thinker10mo ago
If you have a record struct r, with just does
R r2 = r1;
r2.SomeProperty = someValue;
R r2 = r1;
r2.SomeProperty = someValue;
So it doesn't call a constructor or method, it just copies the entire struct memory on the stack.
bacon
bacon10mo ago
with expression - create new objects that are modified copies of ex...
Learn about a with expression that performs nondestructive mutation of C# records and structures. The with keyword provides the means to modify one or more properties in the new object.
MODiX
MODiX10mo ago
Thinker
sharplab.io (click here)
var person = new Person("John Doe", 40);
var person2 = person with { Age = 41 };
record struct Person(string Name, int Age) {
public Person(Person other) : this(other.Name, other.A... {
Console.WriteLine("copy");
}
}
var person = new Person("John Doe", 40);
var person2 = person with { Age = 41 };
record struct Person(string Name, int Age) {
public Person(Person other) : this(other.Name, other.A... {
Console.WriteLine("copy");
}
}
React with ❌ to remove this embed.
Thinker
Thinker10mo ago
Not according to Sharplab at least
Person person = new Person("John Doe", 40);
Person person2 = person;
person2.Age = 41;
Person person3 = person2;
Person person = new Person("John Doe", 40);
Person person2 = person;
person2.Age = 41;
Person person3 = person2;
bacon
bacon10mo ago
this feels like an annoying oversight lol
Thinker
Thinker10mo ago
Ask in #roslyn if you feel like it
bacon
bacon10mo ago
thanks for the confirmation and help though @🌈 Thinker 🌈
Accord
Accord10mo ago
Looks like nothing has happened here. I will mark this as stale and this post will be archived until there is new activity.