Search code examples
c#inheritanceconstructorrecord

C# Initialize inherited record form base record


I have a base record type and an inherited record type which adds a few fields. At runtime I have an instance of the base record type and want to convert it to an instance of the inherited record type, without retyping all the parameters.

I tried the following:

   public record BaseRecord(string firstName, string lastName);
   public record ChildRecord(BaseRecord baseRecord, DateTime dateOfBirth) : BaseRecord(baseRecord);

Now I can do the following:

            var baseRecord = new BaseRecord("John", "Doe");
            var childRecord = new ChildRecord(baseRecord, new DateTime(2000, 1, 1));

But unfortunately the ChildRecord now has a property "baseRecord" of Type BaseRecord, although it is delegated to the base constructor what normaly has the effect that its omitted and not added as a property to the record (at least I thought)

enter image description here

Is there any way to prevent the creation of the "baseRecord" property?

I don't want to write all the fields as in C# create derived record from base record instance

[Clarification]:

Thanks for the answers. I was aware of the different possibilities of implementations.

My goal was, to prevent repeating all the inherited fields, by leveraging the "copy constructor" of the base class. But this caused the inherited class to have an "unwanted" property.

Currently the answer of shingo is the most closest to this goal. I wait a few days before accepting it.


Solution

  • You need to manually add the constructor and property like a regular class.

    public record ChildRecord : BaseRecord
    {
        public DateTime dateOfBirth { get; set; }
    
        public ChildRecord(BaseRecord baseRecord, DateTime dateOfBirth)
            : base(baseRecord)
            => this.dateOfBirth = dateOfBirth;
    }