DEV Community

Juarez Júnior for Develop4Us

Posted on • Edited on

C# Tip: Records with Inheritance

Let’s talk about Records with Inheritance, introduced in C# 9, which allow records to use inheritance, just like classes, providing a more flexible and efficient way to work with immutable data. See the example in the code below.

public record Document(int Id, DateTime Date);

public record Invoice(int Id, DateTime Date, decimal Amount) : Document(Id, Date);

public record Receipt(int Id, DateTime Date, string Payer) : Document(Id, Date);

public class Program
{
    public static void Main()
    {
        Invoice invoice = new(1, DateTime.Now, 150.00m);
        Receipt receipt = new(2, DateTime.Now, "John");

        Console.WriteLine(invoice); // Output: Invoice { Id = 1, Date = ..., Amount = 150.00 }
        Console.WriteLine(receipt); // Output: Receipt { Id = 2, Date = ..., Payer = John }
    }
}
Enter fullscreen mode Exit fullscreen mode

Explanation:

Records are ideal for working with immutable data and for scenarios where you need to compare objects by value, not by reference. With Records with Inheritance, you can create hierarchies of types based on records, which is useful in scenarios where different data types share common properties. Imagine you have an application that handles different types of documents (invoices, receipts, etc.), where all share properties like ID and Date. Using inheritance with records, you can define a base record and derive other specific records.

This approach makes your code cleaner and more organized, while maintaining the benefits of immutability and value comparison.

Code Explanation:

In this example, we have three records:

  1. Document: This is the base record that contains common properties like Id and Date for all document types.
  2. Invoice: This record inherits from Document and adds a specific property, Amount, representing the invoice value.
  3. Receipt: This also inherits from Document and adds a Payer property, representing the person who made the payment.

In the Main method, we create an instance of Invoice and another of Receipt, displaying their values in the console. Each record inherits the common properties from Document (such as Id and Date) and adds its own properties, demonstrating how inheritance simplifies code reuse.

This exemplifies a real-world scenario where different document types share common data but also have their unique attributes. Inheritance in records allows you to efficiently reuse common data while maintaining the immutability and value comparison benefits of records.

Source code: GitHub

I hope this tip helps you use Records with Inheritance to write more organized and efficient code! Until next time.

Top comments (0)