c# with keyword record
"with" keyword is kinda interesting as it allows deep copying. However, it can work with "record" or "struct" (directly). record can have class as its fields as we will see later. It is not possible to have class as shown in the code example here.
You will get error - "he receiver type 'MyRecord' is not a valid record type and is not a struct type".
The following code shows we can copy mix record with class and then do a deep copy using "with" keyword.
var addr = new Address
{
Addresss1 = "125 Don Buck",
Addresss2 = "Massey 0512 Auckland",
State = "Auckland"
};
var addr2 = new Address
{
Addresss1 = "125 Don Buck",
Addresss2 = "Massey 0512 Auckland",
State = "Auckland"
};
var myrec = new MyRecord(1, "jeremy", addr);
var myrec2 = myrec with { id = 2 };
var myrec3 =
myrec with
{
addr = new Address
{ Addresss1 = "123", Addresss2 = "testdemo app" }
};
record MyRecord(int id, string name, Address addr);
class Record
{
public string Name { get; set; }
public int Id { get; set; }
public Address Addr { get; set; }
}
You can use like this:
var mystruct = new MyStruct { Id = 3, Address = addr, Name = "Mark" };
var mystruct2 = mystruct with { Id = 200 };
struct MyStruct
{
public int Id;
public string Name;
public Address Address;
}
Comments