Record inheritance lets you create new records based on existing ones, so you can reuse and extend data easily.
0
0
Record inheritance in C Sharp (C#)
Introduction
When you want to add more details to a simple data record without rewriting it.
When you have a base record and want specialized versions with extra properties.
When you want to keep your data organized with shared and unique parts.
When you want to compare records including inherited properties easily.
Syntax
C Sharp (C#)
public record BaseRecord(string Name, int Age); public record DerivedRecord(string Name, int Age, string Job) : BaseRecord(Name, Age);
The derived record uses a colon : to inherit from the base record.
You must pass base record parameters to the base constructor in the derived record.
Examples
This example shows a
Person record and an Employee record that inherits from it and adds a Position.C Sharp (C#)
public record Person(string Name, int Age); public record Employee(string Name, int Age, string Position) : Person(Name, Age);
Here,
Dog inherits from Animal and adds a Breed property.C Sharp (C#)
public record Animal(string Species); public record Dog(string Species, string Breed) : Animal(Species);
Sample Program
This program creates a Person and an Employee (which inherits from Person). It prints both records showing their data.
C Sharp (C#)
using System; public record Person(string Name, int Age); public record Employee(string Name, int Age, string Position) : Person(Name, Age); class Program { static void Main() { var person = new Person("Alice", 30); var employee = new Employee("Bob", 40, "Manager"); Console.WriteLine(person); Console.WriteLine(employee); } }
OutputSuccess
Important Notes
Records provide built-in value equality, so inherited properties are included in comparisons.
You can override methods like ToString() in derived records if you want custom output.
Summary
Record inheritance lets you build new records from existing ones to reuse and extend data.
Use the colon : syntax to inherit and pass base parameters.
Inherited records keep all base properties and add new ones.