Through the keyword with one can generate a new record with some or all of its properties set to the source's values.
Can we do something similar, but from a base record to another one that extends it?
public record class root {
public string name { get; set; }
}
public record class extended : root {
public string surname { get; set; }
}
//retrieve from root the shared properties
public extended from(root rt, string surname) {
return //???
}
public example() {
root rt = new root() { name = "jhon" };
extended ext = from(root rt, "wick");
}
One could use reflection, or a custom constructor that takes root as a parameter, but i wonder if there is some record-specific shortcut
-EDIT- possible answer
record seems to implement a constructor that takes another instance of itself.
As such i can write:
protected extended(root original, string surname) : base(original) {
this.Surname = surname;
}
avoiding the code repetition
You can go with copy constructors (fiddle):
public record root (string name);
public record extended (string surname, string name) : root (name)
{
public extended(root copy, string surname): this(surname, copy.name) { }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With