DEV Community

Juarez Júnior
Juarez Júnior

Posted on

C# Tip: Sealed Record Classes

Let’s talk about Sealed Record Classes, introduced in C# 10, which allow you to create records that cannot be inherited, maintaining immutability and preventing other types from deriving from them. See the example in the code below.

public sealed record Product(string Name, decimal Price);

// You cannot inherit from Product
//public record Pen(string color) : Product;

public class Program
{
    public static void Main()
    {
        Product product = new("Pen", 2.99m);
        Console.WriteLine($"Product: {product.Name}, Price: {product.Price}");
    }
}
Enter fullscreen mode Exit fullscreen mode

Explanation:

In C# 10, you can now create Sealed Record Classes, which are records that cannot be extended. This is useful when you want to ensure that a specific data structure is immutable and cannot be modified by derived classes. When you mark a record as sealed, you prevent it from being inherited by other types, ensuring that the implementation and data remain unchanged.

This feature is especially useful in scenarios where data security and consistency are crucial, such as working with domain models that should not be altered or extended.

Source code: GitHub

I hope this tip helps you use Sealed Record Classes to protect your models and data! Until next time.

Top comments (0)