Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# create derived record from base record instance

Tags:

c#

record

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

like image 430
Andrea Bardelli Avatar asked Mar 23 '26 01:03

Andrea Bardelli


1 Answers

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) { }
}
like image 150
Sinatr Avatar answered Mar 25 '26 15:03

Sinatr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!