Sealed by default
TheYard is a used-vehicle auction platform built in the open: a .NET 11 API, a React front end, and
two databases underneath it. A class in it is sealed unless something in the solution derives from it.
That is the default rather than a decision taken class by class, and the one class that had slipped
past it was found by counting, not by review, which is the argument for the test at the bottom of this
page.
In plain words
Every class in this code is locked against being extended (sealed, in C#) unless something in the solution actually extends it. A test counts every class on each build and fails on one left open with nothing deriving from it. The page shows why this matters most for records, the classes compared by their values.
What that is worth: a developer can trust that two records with the same values compare as equal, and the organization has that held by the build instead of by a reviewer's memory.
What sealed says
sealed on a class stops any other class deriving from it. The C# reference puts it in one line:
"When applied to a class, the sealed modifier prevents other classes from inheriting from it"
(sealed, C# reference).
A whole class from this repository, the in-memory half of the password reset port, as it is written:
public sealed class MemoryResetLinks : IResetLinks
{
private readonly System.Collections.Concurrent.ConcurrentDictionary<string, (string Token, DateTimeOffset Expires)> _kept = new(StringComparer.Ordinal);
private readonly TimeProvider _clock;
public MemoryResetLinks(TimeProvider? clock = null)
{
_clock = clock ?? TimeProvider.System;
}
public Task<string> KeepAsync(string token, TimeSpan lifetime, CancellationToken cancellation)
{
var now = _clock.GetUtcNow();
foreach (var (id, entry) in _kept)
{
if (entry.Expires <= now)
{
_kept.TryRemove(id, out _);
}
}
string fresh = ResetLinkIds.Fresh();
_kept[fresh] = (token, now.Add(lifetime));
return Task.FromResult(fresh);
}
public Task<string?> ReadAsync(string id, CancellationToken cancellation)
{
if (ResetLinkIds.IsOne(id) && _kept.TryGetValue(id, out var entry) && entry.Expires > _clock.GetUtcNow())
{
return Task.FromResult<string?>(entry.Token);
}
return Task.FromResult<string?>(null);
}
public Task<bool> ForgetAsync(string id, CancellationToken cancellation) =>
Task.FromResult(ResetLinkIds.IsOne(id) && _kept.TryRemove(id, out _));
}
Live from api/TheYard.Application/Features/Accounts/ResetLinks.cs, region memory, read from this build at 99df7a8.
Nothing derives from it and nothing was meant to, and the declaration says so before a reader has to
go looking for a subclass that is not there.
Sealed records, and the comparison they give you
This is the part worth passing on, and it is the reason every record in this repository is sealed on
purpose.
A record is a class the compiler writes equality for. Two records holding the same field values
compare as equal; two ordinary classes holding the same field values do not, because a class compares
references and a record compares members. That difference is the whole reason to reach for a record:
comparing payloads in a test, using a data transfer object as a dictionary key, or deciding whether
anything actually changed.
public sealed class PlainBid
{
public required string VehicleId { get; init; }
public required int Amount { get; init; }
}
public sealed record Bid(string VehicleId, int Amount);
var a = new PlainBid { VehicleId = "v-1", Amount = 9_000 };
var b = new PlainBid { VehicleId = "v-1", Amount = 9_000 };
Console.WriteLine(a == b);
Console.WriteLine(new Bid("v-1", 9_000) == new Bid("v-1", 9_000));
var seen = new HashSet<Bid> { new("v-1", 9_000) };
Console.WriteLine(seen.Contains(new Bid("v-1", 9_000)));
Leave that record unsealed and the compiler hands it something else as well: a protected virtual EqualityContract. That property is how the generated Equals decides whether the object it was
handed is even the same kind of thing, and the C# reference is explicit that it exists for exactly
that
(Records, C# reference).
Derive from your DTO and the compiler overrides the contract for you. Every comparison made against
the base type now means something different, no call site changed, and the place that shows up is
production.
public record Payload(string Id);
public record Audited(string Id, string By) : Payload(Id);
Payload one = new Payload("p-1");
Payload two = new Audited("p-1", "steve");
Console.WriteLine(one == two);
Console.WriteLine(one.Equals(two));
Sealing the record removes that case from the language rather than from a reviewer's memory. Same
values, same thing, and nothing can be derived that changes the answer.
The wire shape of a vehicle, whole, as the site serves it:
namespace TheYard.Data;
public sealed record Vehicle
{
public required string Id { get; init; }
public required string Vin { get; init; }
public required int Year { get; init; }
public required string Make { get; init; }
public required string Model { get; init; }
public required string Trim { get; init; }
public required string BodyStyle { get; init; }
public required string ExteriorColor { get; init; }
public required string InteriorColor { get; init; }
public required string Engine { get; init; }
public required string Transmission { get; init; }
public required string Drivetrain { get; init; }
public required int OdometerKm { get; init; }
public required string FuelType { get; init; }
public required double ConditionGrade { get; init; }
public required string ConditionReport { get; init; }
public required IReadOnlyList<string> DamageNotes { get; init; }
public required string TitleStatus { get; init; }
public required string Province { get; init; }
public required string City { get; init; }
public required string AuctionStart { get; init; }
public required int StartingBid { get; init; }
public required int? ReservePrice { get; init; }
public required int? BuyNowPrice { get; init; }
public required IReadOnlyList<string> Images { get; init; }
public required string SellingDealership { get; init; }
public required string Lot { get; init; }
public required int? CurrentBid { get; init; }
public required int BidCount { get; init; }
}
Live from api/TheYard.Data/Vehicle.cs, region *, read from this build at 99df7a8.
Two things in that file are worth the read. The sealing reason is written on the type itself rather
than left to a page, and the comment is honest about the exception: two of the properties are
IReadOnlyList<string>, and the default comparer for an interface calls the instance's own Equals,
which for a list is reference equality. Twenty-seven fields compare by value and two compare by
identity, and a test that needs those two compared by contents has to say so.
Record structs cannot be derived from at all, so they get the same guarantee from the runtime.
Habits do not carry from one busy month to the next, which is why this is a test rather than a
rule. Every build checks it, and anything that has to stay open goes on a named allow-list with the
reason written beside it. The test is at the bottom of this page, whole.
Why this codebase seals by default
Intent comes first. An open class is an invitation: somebody may reasonably derive from it, override
a method, and expect the rest of the code to keep working. These classes were not written to survive
that. Most of them do one job behind a port, like the null sender that stands in when a container has
no mail configured:
public interface IEmailSender
{
bool Configured { get; }
string Reason { get; }
Task<bool> SendAsync(string to, string subject, string text, CancellationToken cancellation);
}
public sealed class NullEmailSender(string reason) : IEmailSender
{
public static readonly NullEmailSender Instance = new("no email sender is configured on this site; the operator can mint a reset link from the Admin tab");
public bool Configured => false;
public string Reason => reason;
public Task<bool> SendAsync(string to, string subject, string text, CancellationToken cancellation) => Task.FromResult(false);
}
Live from api/TheYard.Application/Features/Accounts/Email.cs, region email-port, read from this build at 99df7a8.
The interface is the extension point, and the class behind it is finished. That is the shape almost
everything here takes, and sealing is how the class says which of the two it is.
The runtime gets something out of it as well. When the just-in-time compiler knows a type has no
subclass, it can turn virtual calls into direct ones, and casts, type checks, array assignments and
span conversions all get cheaper. Gérald Barré measured each of those
(Performance benefits of sealed class in .NET).
His numbers are his, from his machine, and none of them are copied onto this page: a figure this
project cannot measure through its own gate is a figure it should not print.
An analyzer catches the half a person forgets. CA1852 names an internal class that nothing derives
from and that could be sealed
(CA1852: Seal internal types).
It is on here as a warning:
dotnet_diagnostic.CA1852.severity = warning
Live from .editorconfig, region ca1852, read from this build at 99df7a8.
The gate reads any warning as red, so that rule is held by the build rather than by anybody's
attention. CA1852 stops at internal classes, which is why the test below covers the public ones too.
The same class open and sealed, and what a caller can do with each:
public class Increment
{
public virtual int For(int standing) => standing < 10_000 ? 250 : 1_000;
}
public sealed class Generous : Increment
{
public override int For(int standing) => 1;
}
public sealed class SealedIncrement
{
public int For(int standing) => standing < 10_000 ? 250 : 1_000;
}
When not to seal
The Framework Design Guidelines say the opposite of this page: "DO NOT seal classes without having a
good reason"
(Sealing). That advice
is written for public libraries, where a type other people derive from is part of the contract and
sealing it later breaks strangers who already shipped. Nothing here is a library. These six projects
are one application, everything that derives from anything is in the same solution, and unsealing a
class the day somebody needs to is one keyword in one commit.
So the rule carries its exception in writing. A class with a subclass stays open. A class that has to
stay open for a reason the code cannot show goes on a named allow-list inside the test, with the
reason beside it, which is a decision somebody made rather than one nobody noticed.
The one base class in this repository written to be inherited is a test base that three test classes
share
(api/TheYard.Tests/AuthTests.cs).
It is abstract, which says the same thing from the other side: this class exists to be derived from
and cannot be used on its own. A base written to be open looks like this:
public abstract class StoreCheck
{
protected StoreCheck(TimeProvider clock) => Clock = clock;
protected TimeProvider Clock { get; }
protected abstract Task<bool> IsReachableAsync(CancellationToken cancellation);
public async Task<(string Name, bool Healthy, long At)> RunAsync(CancellationToken cancellation)
{
bool reachable = await IsReachableAsync(cancellation);
return (GetType().Name, reachable, Clock.GetUtcNow().ToUnixTimeMilliseconds());
}
}
The test that holds it
One test class reads the six projects that make up the application, counts the shape of every class
and record the build actually has, and fails when one of them is open with nothing deriving from it:
using System.CodeDom.Compiler;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text.RegularExpressions;
namespace TheYard.Tests;
public class SealedByDefaultTests
{
private static readonly string[] Projects =
[
"TheYard.Data",
"TheYard.Domain",
"TheYard.Application",
"TheYard.Infrastructure",
"TheYard.Infrastructure.Cosmos",
"TheYard.Api",
];
private static readonly Dictionary<string, string> Open = new(StringComparer.Ordinal)
{
};
private static List<Type> Written() =>
Projects
.SelectMany(name => Assembly.Load(new AssemblyName(name)).GetTypes())
.Where(IsWrittenHere)
.ToList();
private static bool IsWrittenHere(Type type) =>
OneOfOurs(type)
&& !(type.FullName ?? string.Empty).Contains('<', StringComparison.Ordinal)
&& !IsGenerated(type)
&& !typeof(Delegate).IsAssignableFrom(type);
private static bool OneOfOurs(Type type) =>
type.Namespace is null
|| type.Namespace.StartsWith("TheYard", StringComparison.Ordinal);
private static bool IsGenerated(Type type) =>
type.IsDefined(typeof(CompilerGeneratedAttribute), inherit: false)
|| type.IsDefined(typeof(GeneratedCodeAttribute), inherit: false)
|| (type.DeclaringType is not null && IsGenerated(type.DeclaringType));
private static bool IsRecord(Type type) =>
type.GetMethod("<Clone>$", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) is not null
|| (type.IsValueType
&& type.GetMethod("PrintMembers", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) is not null);
private static string Shape(Type type)
{
if (IsRecord(type))
{
return "records";
}
if (!type.IsClass)
{
return string.Empty;
}
if (type.IsAbstract && type.IsSealed)
{
return "static";
}
if (type.IsAbstract)
{
return "abstract";
}
return type.IsSealed ? "sealed" : "open";
}
private static Dictionary<string, int> Counted()
{
var counts = new Dictionary<string, int>(StringComparer.Ordinal)
{
["sealed"] = 0,
["static"] = 0,
["abstract"] = 0,
["open"] = 0,
["records"] = 0,
["open records"] = 0,
};
foreach (Type type in Written())
{
string shape = Shape(type);
if (counts.ContainsKey(shape))
{
counts[shape]++;
}
if (shape == "records" && !type.IsSealed)
{
counts["open records"]++;
}
}
return counts;
}
[Fact]
public void Every_class_in_the_application_is_sealed_static_abstract_or_inherited()
{
var written = Written();
Assert.True(written.Count > 100, $"only {written.Count} types were read across {Projects.Length} projects");
var everything = written
.Concat(typeof(SealedByDefaultTests).Assembly.GetTypes())
.ToList();
var unexplained = new List<string>();
foreach (Type type in written.Where(type => Shape(type) == "open"))
{
bool inherited = everything.Any(other => other != type && other.BaseType == type);
if (inherited || Open.ContainsKey(type.FullName ?? type.Name))
{
continue;
}
unexplained.Add(
$"{type.FullName} is open, nothing in the solution derives from it, "
+ "and it is not on the allow-list in this file");
}
Assert.True(unexplained.Count == 0, string.Join(Environment.NewLine, unexplained));
}
[Fact]
public void Every_record_is_sealed_so_two_of_them_compare_by_value_alone()
{
var open = Written()
.Where(type => IsRecord(type) && !type.IsSealed)
.Select(type => $"{type.FullName} is an open record, so its equality carries the runtime type")
.ToList();
Assert.True(open.Count == 0, string.Join(Environment.NewLine, open));
}
[Fact]
public void The_allow_list_holds_no_entry_that_has_stopped_being_open()
{
var written = Written();
var stale = new List<string>();
foreach (string name in Open.Keys)
{
Type? listed = written.Find(candidate => candidate.FullName == name);
if (listed is null || Shape(listed) != "open")
{
stale.Add($"{name} is on the allow-list and is not an open class in these projects");
}
}
Assert.True(stale.Count == 0, string.Join(Environment.NewLine, stale));
}
[Fact]
public void The_page_quotes_the_shape_this_build_has()
{
string page = File.ReadAllText(Path.Combine(Repo.Root(), "docs", "best-practices", "SEALED.md"));
var wrong = new List<string>();
foreach ((string shape, int actual) in Counted())
{
var quoted = Regex.Match(page, $@"^\| {shape} \| (\d+) \|", RegexOptions.Multiline);
if (!quoted.Success)
{
wrong.Add($"docs/best-practices/SEALED.md has no row for {shape}");
continue;
}
if (int.Parse(quoted.Groups[1].Value) != actual)
{
wrong.Add($"docs/best-practices/SEALED.md says {quoted.Groups[1].Value} {shape} and this build has {actual}");
}
}
Assert.True(wrong.Count == 0, string.Join(Environment.NewLine, wrong));
}
[Fact]
public void The_analyzer_that_catches_the_internal_half_is_on_as_a_warning()
{
string editorconfig = File.ReadAllText(Path.Combine(Repo.Root(), ".editorconfig"));
Assert.Contains("dotnet_diagnostic.CA1852.severity = warning", editorconfig, StringComparison.Ordinal);
Assert.Contains("CA1852", File.ReadAllText(Path.Combine(Repo.Root(), "docs", "best-practices", "SEALED.md")), StringComparison.Ordinal);
}
}
Live from api/TheYard.Tests/SealedByDefaultTests.cs, region *, read from this build at 99df7a8.
Measured on this build:
Every class in those six projects is sealed or static, and a static class cannot be inherited either,
which is why the open and abstract rows read 0. Every record is sealed or a record struct, so value
comparison means what it says on every one of them. Every number in that table is read back out of this page by the
test above, so it cannot drift from the build the way a number typed once always does.