Design rules
API shape, sealed types, and dependency injection.
Rules
| Rule | Title | Code fix |
|---|---|---|
| E128001 | Use FileInfo/DirectoryInfo instead of string paths | Yes |
| E128003 | Use TimeProvider instead of DateTime.Now / DateTimeOffset.Now | Yes |
| E128004 | Use IHttpClientFactory instead of new HttpClient() | Yes |
| E128005 | Seal classes that have no subclasses | Yes |
| E128007 | Avoid async void methods (non-event-handler) | Yes |
| E128008 | Avoid sync-over-async (.Result / .GetAwaiter().GetResult()) | Yes |
| E128017 | Use primary constructor parameter directly | Yes |
| E128019 | Do not pass CancellationToken by in reference | Yes |
| E128021 | Do not use in modifier with ref struct parameters (default: Error) | Yes |
| E128030 | Do not compare FileSystemInfo types by reference (default: Info) | Yes |
| E128032 | Concrete-only DI registration with available interface | Yes |
| E128036 | Task.Run wrapping async lambda — unnecessary thread pool hop | Yes |
| E128042 | Convert.ToInt32/ToInt64 wrapping ExecuteScalar without null guard | Yes |
| E128044 | Type implements IAsyncDisposable but not IDisposable | Yes |
| E128045 | Avoid direct System.Console usage | No |
| E128046 | Class has excessive user-defined inheritance depth | No |
| E128048 | Use switch instead of if/else-if chain on enum values | Yes |
| E128049 | Avoid [DynamicallyAccessedMembers] — suppress with justification if required | Yes |
| E128050 | Use TimeSpan for time-duration values to avoid unit ambiguity (default: Error) | Yes |
| E128052 | Use immutable collection interface instead of mutable concrete type (default: Info) | Yes |
| E128053 | Use collection of FileInfo/DirectoryInfo instead of collection of string for file system paths | Yes |
| E128058 | Return List<T> via .AsReadOnly() when exposing as IReadOnlyList<T> | Yes |
| E128059 | Interface method parameter is unused in implementation (default: Error) | Yes |
| E128060 | Return Dictionary<K,V> via .AsReadOnly() when exposing as IReadOnlyDictionary<K,V> | Yes |
| E128061 | Use an immutable type for static readonly arrays | Yes |
| E128074 | Readonly struct property should use init accessor | Yes |
| E128080 | Use ByteSize for data-size values to avoid unit ambiguity (default: Error) | Yes |
| E128082 | Do not unwrap ByteSize via cast | Yes |
| E128087 | Static numeric field should not be incremented with ++/-- | Yes |
| E128218 | State encoded across several members (default: Info) | No |
| E128219 | Memberless abstract base with all derivation in one assembly should be closed | Yes |
| E128220 | Union switch ends in a discard or var arm instead of a null arm | Yes |
| E128221 | Union Value read or case cast outside a pattern match | No |
| E128225 | Abstract base with members is a closed hierarchy | Yes |
| E128232 | The dynamic keyword defeats compile-time type checking | No |
| E128257 | Bound options property is not public | No |
| E128259 | Type name is the plural of a sibling type (default: Info) | No |
| E128262 | IHttpContextAccessor injected into a plain service (default: Info) | No |
Rule details
E128001: File system path types
Flags string parameters, Option<string>, and Argument<string> that look like file system paths (by name or usage). Suggests FileInfo or DirectoryInfo instead.
// Before (warns)
void Save(string filePath) { }
// After
void Save(FileInfo filePath) { }
E128003: TimeProvider over DateTime
Flags DateTime.Now, DateTime.UtcNow, DateTime.Today, DateTimeOffset.Now, and DateTimeOffset.UtcNow. These are untestable — inject TimeProvider via DI instead.
// Before (warns)
var now = DateTime.UtcNow;
// After — inject TimeProvider
var now = timeProvider.GetUtcNow().UtcDateTime;
E128004: IHttpClientFactory
Flags new HttpClient(). Direct instantiation leaks sockets and ignores DI-managed handlers.
The code fix replaces the call with CreateClient() on an IHttpClientFactory field. It reuses a nonnullable factory field only when every constructor assigns that field from a parameter before any other work. A new factory assignment goes first in the constructor body. The fix applies only in an instance member of a class with a supported constructor. It declines a class with a custom base type unless the class is sealed and declares no override or interface implementation. It also declines initializers, static code, structs, records, a name that a local or parameter shadows, and unsupported constructor shapes. Fix All is unavailable.
E128005: Sealed by default
Flags non-abstract, non-static classes with no derived types in the compilation. Sealing enables devirtualization and communicates design intent. The rule never reports a class that any type parameter, method, or local function names as a generic constraint, because a sealed class cannot be a constraint (CS0701).
// Before (warns)
public class MyService { }
// After
public sealed class MyService { }
E128007: Async void
Flags async void methods that are not event handlers. Exceptions in async void crash the process.
// Before (warns)
async void LoadData() { await db.QueryAsync(); }
// After
async Task LoadData() { await db.QueryAsync(); }
E128008: Sync-over-async
Flags .Result, .GetAwaiter().GetResult(), and .Wait() on tasks. These block the calling thread and risk deadlocks.
// Before (warns)
var data = httpClient.GetAsync("/api").Result;
// After
var data = await httpClient.GetAsync("/api");
E128017: Primary constructor backing field
Flags fields that are identity assignments from primary constructor parameters. Use the parameter directly in method bodies instead of creating a redundant backing field.
// Before (warns)
public class Service(ILogger logger)
{
private readonly ILogger _logger = logger;
public void Run() => _logger.LogInformation("running");
}
// After
public class Service(ILogger logger)
{
public void Run() => logger.LogInformation("running");
}
E128019: CancellationToken by in reference
Flags in CancellationToken parameters. The in modifier makes CancellationToken a by-ref parameter, which breaks reflection-based frameworks (e.g., Microsoft.Extensions.AI). CancellationToken is a small struct — pass it by value.
// Before (warns)
async Task RunAsync(in CancellationToken ct) { }
// After
async Task RunAsync(CancellationToken ct) { }
E128021: in modifier with ref structs
Flags in on ref struct parameters (Span<T>, ReadOnlySpan<T>, etc.). Ref structs are already passed by reference — in is redundant and a compile error on extension method this parameters. Default severity: Error.
// Before (error)
void Read(in ReadOnlySpan<byte> buffer) { }
// After
void Read(ReadOnlySpan<byte> buffer) { }
E128030: FileSystemInfo reference equality
Flags ==, !=, and .Equals() comparisons on FileInfo and DirectoryInfo. These types do not override Equals or operator==, so comparisons use reference equality from System.Object — two objects pointing to the same path are never equal. Compare .FullName instead. Default severity: Info.
// Before (warns)
if (fileA == fileB) { }
// After
if (string.Equals(fileA.FullName, fileB.FullName, StringComparison.Ordinal)) { }
E128032: Concrete-only DI registration
Flags AddScoped<ConcreteType>() / AddTransient<ConcreteType>() / AddSingleton<ConcreteType>() when the concrete type implements a non-marker interface. Register as that interface to enable testing and substitution. The code fix offers one action per interface, and it writes the type arguments and the qualification, so a generic type converts cleanly.
E128036: Task.Run wrapping async lambda
Flags Task.Run(async () => ...). For I/O-bound work, the thread pool hop is unnecessary overhead — just call the async method directly. Task.Run is for CPU-bound work.
E128042: ExecuteScalar null guard
Flags Convert.ToInt32(cmd.ExecuteScalar()) and similar patterns without a null check. ExecuteScalar returns null when there are no rows, causing an InvalidCastException.
E128044: IAsyncDisposable without IDisposable
Flags types that implement IAsyncDisposable but not IDisposable. Consumers using synchronous using will silently skip disposal. The code fix adds IDisposable to the base list, and adds a Dispose() stub only when the type does not already declare one.
E128045: Direct System.Console usage
Flags direct use of System.Console members. Use ILogger for service code or ITerminalWriter/ITerminalPrompt for CLI code instead. No code fix — the replacement depends on context.
E128046: Excessive inheritance depth
Flags classes with 3 or more levels of user-defined inheritance (excluding framework base classes). Set e128_max_inheritance_depth to change the threshold. Deep hierarchies are fragile and hard to reason about. No code fix.
E128048: Enum if/else-if chain
Flags if/else-if chains comparing the same variable against enum constants. A switch statement is more readable and the compiler can warn about missing cases.
E128049: DynamicallyAccessedMembers guard
Flags usage of [DynamicallyAccessedMembers] attribute. This attribute opts out of trimming safety. Suppress with a justification comment if required for HttpClientFactory or JSON discriminated unions.
E128050: TimeSpan for durations
Flags int or double parameters/properties with names like timeout, delay, interval, or duration. Use TimeSpan to avoid unit ambiguity (seconds vs milliseconds). Default severity: Error.
E128052: Mutable collection exposure
Flags public/protected members returning mutable concrete collection types (List<T>, Dictionary<TKey, TValue>, etc.) instead of immutable interfaces (IReadOnlyList<T>, IReadOnlyDictionary<TKey, TValue>). Default severity: Info.
E128053: Collection of file system path strings
Flags IEnumerable<string>, List<string>, string[] etc. parameters and properties with path-like names. Use IEnumerable<FileInfo> or IEnumerable<DirectoryInfo> instead.
E128058: Return List<T> via .AsReadOnly()
Flags methods that return a List<T> field directly when the declared return type is IReadOnlyList<T> or IReadOnlyCollection<T>. It also covers a Task<T> or ValueTask<T> return that carries the interface. Callers can cast back to List<T> and mutate the internal list. Use .AsReadOnly() to return a true read-only wrapper.
// Before (warns)
public IReadOnlyList<string> Items => _items;
// After
public IReadOnlyList<string> Items => _items.AsReadOnly();
E128059: Unused interface method parameter
Flags interface method implementations where a parameter declared in the interface contract is never referenced in the implementation body. The interface promises callers that the parameter affects behavior; ignoring it silently violates that contract.
// Before (error)
public string Format(string input, IFormatProvider? provider) =>
input.ToUpperInvariant(); // provider is ignored
// After — rename unused parameter to _ to signal intent
public string Format(string input, IFormatProvider? _) =>
input.ToUpperInvariant();
E128060: Return Dictionary<K,V> via .AsReadOnly()
Flags methods and properties that return a Dictionary<K,V> field directly when the declared return type is IReadOnlyDictionary<K,V>, including a Task<T> or ValueTask<T> return that carries the interface. Callers can cast back to Dictionary<K,V> and mutate the internal collection. Use .AsReadOnly() (requires .NET 9+) or wrap in ReadOnlyDictionary<K,V>.
// Before (warns)
public IReadOnlyDictionary<string, int> Counts => _counts;
// After
public IReadOnlyDictionary<string, int> Counts => _counts.AsReadOnly();
E128061: Static readonly array should be immutable
Flags private static readonly T[] and internal static readonly T[] fields. Arrays are reference types — readonly prevents reassignment but callers can still mutate contents via the indexer.
An initializer of constant byte values becomes a ReadOnlySpan<byte> property. The compiler stores those bytes as read-only data, so the property allocates nothing and copies nothing. Every other element type becomes ImmutableArray<T>.
// Before (warns)
private static readonly string[] Names = ["a", "b"];
private static readonly byte[] Magic = [0x50, 0x4B, 0x03, 0x04];
// After
private static readonly ImmutableArray<string> Names = ["a", "b"];
private static ReadOnlySpan<byte> Magic => [0x50, 0x4B, 0x03, 0x04];
E128074: Readonly struct property should use init accessor
Flags properties in readonly struct types that use a private setter instead of an init accessor. Properties with private setters in readonly structs allow mutation at construction time but do not communicate immutability to callers. Use init to make the intent explicit and enforce immutability post-construction.
// Before (warns)
public readonly struct Point
{
public int X { get; private set; }
}
// After
public readonly struct Point
{
public int X { get; init; }
}
E128080: Use ByteSize for data-size values
Flags a numeric property, parameter, field, or local variable whose name ends with a data-size suffix. The suffix list covers Bytes, Kb, Kilobytes, Mb, Megabytes, Gb, Gigabytes, Tb, Terabytes, FileSize, MaxSize, CacheSize, BufferSize, and ChunkSize. A nullable numeric reports too. Members declared inside a type named ByteSize are exempt. The rule matches that type by simple name, whatever its namespace. The rule reports at error. The code fix resolves the ByteSize type in the compilation, so a namespace move does not break the rewritten call.
// Before (error)
public int MaxBufferSizeMb { get; init; }
// After
public ByteSize MaxBufferSize { get; init; }
E128082: Do not unwrap ByteSize via cast
Flags a cast to a numeric type of a Bytes, Bits, Kilobytes, Megabytes, Gigabytes, or Terabytes property on a ByteSize value. The rule matches that type by simple name, whatever its namespace. The cast removes the unit from the type system. Compare ByteSize values directly, or format the value.
// Before (warns)
if ((long)limit.Bytes > 1024) { }
// After
if (limit > threshold) { }
E128087: Static numeric field should not be incremented with ++/--
Flags static numeric fields mutated with ++, --, +=, or -=. These operations are not atomic — concurrent invocations produce data races, and the accumulated value leaks across call contexts. Use Interlocked.Increment/Decrement/Add for int/long fields, or remove the static keyword.
// Before (warns)
private static int _count;
void Track() => _count++;
// After — atomic
private static int _count;
void Track() => Interlocked.Increment(ref _count);
E128218: State encoded across several members
Flags a class or a struct that encodes one state with several members. The rule reports four shapes.
- A cluster of mutable
boolmembers. One method writes two or more members with different values, or one condition reads two or more members and at least one read is negated. - A lifecycle pair. Two mutable
boolmembers are set only totrue, are read in a condition, carry lifecycle names, and are written in different bodies. - A nullable union. A nullable member is tested for
null, and the non-null branch tests oneboolmember of its type. - A nullable member beside a lifecycle
bool. One condition reads both, and the nullable member takes a null and a non-null value.
A bool cluster member counts only when its transitions are not one-way. A write in a constructor or a destructor is not a transition. A write through Interlocked.Exchange, Interlocked.CompareExchange, Volatile.Write, Unsafe.AsRef, Unsafe.As, or a ref local alias is a transition.
The rule analyzes fields, auto-properties, and a property pair that forwards to one field. The field is the canonical member, so the pair counts once. A write from another type through a public setter counts only when the owning type also has an internal transition. A readonly struct and a record struct stay out of the bool cluster. A record still reports a nullable union.
The default minimum member count is two. Set e128_min_state_flags in .editorconfig to change it. The minimum accepted value is two. Set e128_state_min_transition_bodies to require more than one transition body. The default is one. A two-member bool cluster always needs two transition bodies and one body that writes both true and false. The rule reads both options per source file, so a project-level .editorconfig applies. The rule stays at Info because a pair of independent flags can look like one state at a single call site.
// Before (info)
private bool _isRunning;
private bool _isPaused;
private bool _isStopped;
public void Start()
{
_isStopped = false;
_isRunning = true;
}
public void Pause()
{
_isRunning = false;
_isPaused = true;
}
public void Stop()
{
_isPaused = false;
_isStopped = true;
}
// After
private State _state;
public void Start() => _state = State.Running;
public void Pause() => _state = State.Paused;
public void Stop() => _state = State.Stopped;
No code fix. The state names and the legal transitions are domain decisions.
E128219: Memberless abstract base is a closed hierarchy
Flags an internal abstract class or record base that declares no members while every type that derives from it lives in the same assembly. The closed modifier names that shape, and a switch over the closed hierarchy then fails the build on a missing case through CS8509.
A base that carries members, a positional record whose parameter list carries state, or a base without a derived type stays silent. A public base stays silent too, because an assembly outside the compilation may derive from it and a closed modifier would break that derivation. An assembly that grants a friend InternalsVisibleTo access stays silent for the same reason.
The code fix replaces the abstract modifier with closed.
// Before (warns)
internal abstract class GreetingState { }
internal sealed class Greeted : GreetingState { }
// After
internal closed class GreetingState { }
internal sealed class Greeted : GreetingState { }
E128220: Union switch ends in a discard arm
Ships in the Roslyn 5.12 build, so it needs the .NET SDK 11.0 or later.
Flags a switch over a union whose last arm is a discard or var arm and which carries no null arm. The null arm names the empty case, so the compiler keeps warning when a case type is added later. A discard or var arm accepts any case type the union grows, and the missing-case warning disappears.
A switch that already ends in a null arm stays silent. A switch over an enum or a plain type stays silent.
A when guard never closes a discard or var arm, so a guarded arm such as _ when condition reports too.
The code fix replaces a discard arm with a null constant pattern. A var arm binds the case value, so the fix stays absent for it and the arm needs a manual edit. A guarded discard arm keeps the guard on the arm, so the fix stays absent for it too.
// Before (warns)
var text = result switch
{
Greeting greeting => greeting.Message,
GreetingError error => error.Message,
_ => "Unknown result."
};
// After
var text = result switch
{
Greeting greeting => greeting.Message,
GreetingError error => error.Message,
null => "Unknown result."
};
E128221: Union case read outside a pattern match
Ships in the Roslyn 5.12 build, so it needs the .NET SDK 11.0 or later.
Flags a Value read on a union expression and a cast of a union expression to a case type. A Value read boxes the case and skips the case set, and a cast trusts the runtime state instead of the type system. A case pattern reads the value without boxing and stays checked against the case list. A compiler-declared union exposes no TryGetValue member, so the pattern is the only checked read.
A member access whose receiver is not a union stays silent, so a Dictionary<K,V>.Values read or a Task result never reports.
No code fix. The rewrite changes control flow, so the developer writes the pattern.
// Before (warns)
if (result.Value is Greeting greeting) { }
var cast = (GreetingError)result;
// After
if (result is Greeting greeting) { }
if (result is GreetingError error) { }
E128225: Abstract base with members is a closed hierarchy
Flags an internal abstract class that declares members while every type that derives from it lives in the same assembly. The closed modifier implies abstract, so a base that declares abstract members keeps them, and the compiler reports CS8509 on a switch that misses a leaf.
The memberless base belongs to E128219. A public base stays silent, because an assembly outside the compilation may derive from it. An assembly that grants a friend InternalsVisibleTo access stays silent for the same reason. A record declaration stays silent, because the compiler synthesizes members from the parameter list and the equality contract.
The code fix replaces the abstract modifier with closed.
// Before (warns)
internal abstract class Shape
{
internal abstract int Area();
}
// After
internal closed class Shape
{
internal abstract int Area();
}
E128232: The dynamic keyword defeats compile-time type checking
Flags the dynamic keyword in a type position. Dynamic dispatch defers every member check to the runtime binder, and the shape blocks trimming and AOT. A concrete type restores compile-time checking.
The rule reads the syntax position through the language grammar, so it covers locals, parameters, return types, lambda return types, generic arguments, casts, and is expressions. A semantic gate compares the bound type against the builtin dynamic type, so a user-defined type named dynamic stays silent. The rule carries no code fix, because the replacement type carries application intent.
// Before (warns)
dynamic payload = Parse(body);
return payload.Value;
// After
JsonNode payload = Parse(body);
return payload["Value"];
E128257: Bound options property is not public
Flags a property that is not public on a type bound by AddOptions<T>().Bind(...), AddOptions<T>().BindConfiguration(...), or services.Configure<T>(...). The binder and ValidateDataAnnotations() read public instance properties only, so a non-public property keeps its default value and ignores the configuration key. The rule also flags a public property with a non-public getter. It stays silent when the registration passes an Action<BinderOptions> that sets BindNonPublicProperties. No code fix, because making a private property public changes the API.
E128259: Type name is the plural of a sibling type
Flags a type whose name is the plural of a sibling type in the same namespace, when the type is not a collection. An operation type named FetchCommands beside FetchCommand reads as a collection of the sibling. Default severity is Info. No code fix, because a rename spans the solution.
E128262: IHttpContextAccessor injected into a plain service
Flags an IHttpContextAccessor constructor parameter on a type that is not a middleware, an MVC or Razor Pages filter, an authorization handler, a Blazor component, or an IHostedService. The accessor hides a dependency on the ambient request and returns null outside a request. Default severity is Info. No code fix.