Reliability rules

Async, cancellation, disposal, and process lifetime.

Rules

RuleTitleCode fix
E128011[GeneratedRegex] missing matchTimeoutMillisecondsYes
E128012RegexOptions.Compiled is redundant in [GeneratedRegex]Yes
E128013[GeneratedRegex] pattern has repeated wildcardsYes
E128014[GeneratedRegex] pattern has a repeated group that can split across iterationsYes
E128016DateTime.Parse/ParseExact missing DateTimeStyles parameterYes
E128020Do not use in modifier with mutable structsYes
E128023Avoid hardcoded /tmp pathYes
E128028Task.FromResult wraps sync I/O that has an async alternativeYes
E128031AddSingleton factory returns IDisposableYes
E128033Options class bound via .Bind() has init-only propertyYes
E128034Constructor news a DI-registered type — inject via DI insteadYes
E128035Concrete-type DI dependency without direct registrationYes
E128037Unbounded Task.WhenAll over async Select or a Task.Run listYes
E128038Task.WhenAll async lambda missing CancellationToken propagationYes
E128039Catch filter must exclude OperationCanceledExceptionYes
E128040Concurrency limit must be positiveYes
E128041JsonDocument.RootElement must not escape the document’s using scopeYes
E128051Broad catch in async HttpClient method missing OperationCanceledException handlerYes
E128056File existence check TOCTOU race conditionYes
E128057Unprotected cleanup in finally blockYes
E128064Disk write-then-read round-trip — use the in-memory value instead of reading backYes
E128070Pool Rent() capacity must be bounded — guard with Math.MinYes
E128076Materialize QuerySelectorAll result before iteratingYes
E128077TextContent string match requires a preceding length guardYes
E128078GetAttribute("href") on element that does not carry hrefNo
E128079CompositeDetection with single generic ID selector lacks specificityNo
E128086ArrayPool buffer used as SqliteParameter value without SizeYes
E128089Avoid bare .Parse() — use TryParse to handle invalid inputNo
E128092Use async File.*Async overload instead of sync methodYes
E128093Use async DbConnection/DbCommand *Async overload instead of sync methodYes
E128096Detect synchronous call to async local function via .Result or .Wait()Yes
E128099Wait for process exit with a provable timeoutYes
E128100Catch filter reads negated token state on OperationCanceledExceptionYes
E128101Verify process output file exists before useYes
E128103DI resolve or named HttpClient resolve with no registrationNo
E128109stackalloc must be bounded and outside loopsYes
E128110Zero a pooled buffer in a finally block before ReturnYes
E128111Pooled buffer used after ReturnNo
E128154Singleton service depends on a scoped service or DbContextNo
E128155Mutating the loop source inside its own foreachYes
E128159TaskCompletionSource without RunContinuationsAsynchronouslyYes
E128161Path.Combine with a rooted or parent segmentYes
E128162Local used after an explicit DisposeNo
E128163ImmutableArray field left at its defaultYes
E128170Split(...)[n] index with no length guardNo
E128171Committed Assert.Fail red-phase stubNo
E128172catch swallows an assertion failureYes
E128173[SuppressMessage] or [ExcludeFromCodeCoverage] with no justificationNo
E128174Constructor past the e128_max_ctor_dependencies ceilingNo
E128175SemaphoreSlim wait with no finally release guaranteeYes
E128176Event subscription that keeps the subscriber aliveYes
E128177Report a record member with a mutable collection typeNo
E128178Report two members that map to one JSON property name (default: Error)No
E128179Options type bound from configuration with no validation callYes
E128181HttpClient.Timeout set to an infinite value hangs the callerNo
E128182IAsyncEnumerable value enumerated twiceNo
E128183Task.WhenAny result is never awaitedNo
E128186Await inside a finally blockNo
E128188Exception filter reads the message textNo
E128189GCHandle with no Free callYes
E128190FileStream created without asynchronous I/OYes
E128192GetBuffer on a MemoryStream with a hidden bufferNo
E128193Disposable field overwritten in a loop without a disposeNo
E128194Lazy<T> field without thread safetyYes
E128195Configuration key absent from the appsettings filesNo
E128196JsonSerializerOptions mutated after first useNo
E128197Fixed day count used as a calendar month (default: Info)No
E128198Substring count built from a length minus a constantNo
E128234A FileStream position is shared across parallel readersNo
E128238Array comparison uses reference equality, not element equalityYes
E128239Stream.Read count discarded before a later buffer readNo
E128240Blocking call inside a lock bodyNo
E128243Span over a list invalidated by a later mutationNo
E128244Zero guard after the divisionNo
E128245Enum cast outside the member setNo
E128246Flags member value is not a power of twoNo
E128248Loop counter is a float or doubleNo
E128250Private field assignment overwritten before a readYes
E128251Loop has no exit pathNo
E128258Service lookup throws a generic exception with no keyNo
E128260Retained memory is read after its owner is disposedNo
E128269Declaration syntax read without a syntax tree checkYes
E128270Rented pooled buffer is never returnedYes

Rule details

E128011: GeneratedRegex timeout

Flags [GeneratedRegex] attributes without matchTimeoutMilliseconds. Without a timeout, catastrophic backtracking on malicious input can hang the process indefinitely.

// Before (warns)
[GeneratedRegex(@"\d+")]
private static partial Regex DigitsOnly { get; }

// After
[GeneratedRegex(@"\d+", RegexOptions.None, Timeout.Infinite)]
private static partial Regex DigitsOnly { get; }

E128012: GeneratedRegex Compiled

Flags RegexOptions.Compiled in [GeneratedRegex]. The source generator ignores this flag — it produces compiled code at build time.

// Before (warns)
[GeneratedRegex(@"\d+", RegexOptions.Compiled, 1000)]

// After
[GeneratedRegex(@"\d+", RegexOptions.None, 1000)]

E128013: Overlapping quantifiers

Flags [GeneratedRegex] patterns where \s* or \s+ is adjacent to a quantifier whose character set overlaps (e.g., .*, .+). This creates quadratic backtracking risk. The rule counts three or more unbounded . quantifiers in one sequence. Wildcards in separate lookarounds, separate atomic groups, or separate alternation branches do not add up, and a pattern with RegexOptions.NonBacktracking stays silent.

E128014: Nested quantifiers

Flags [GeneratedRegex] patterns with nested quantifiers (e.g., (.+)+, (\w+)+, (a*)*) whose first and last consuming atom can match the same text. These cause exponential backtracking on non-matching input. A repeated group whose leading separator atom is a character the trailing atom cannot match stays silent, such as (?:/[^/]+)+. A trailing character class is checked by membership, so (?:/[^\s:"']+)+ still fires: the class matches the /. A bounded {n,m} outer repeat and an atomic (?>...) group also stay silent. An escaped literal is read as an atom, so (\w+\))+ and a markdown-link group with \( and \) stay silent. Two character classes are compared by membership, so ([ab]+[cd])+ stays silent. A pattern with RegexOptions.NonBacktracking stays silent.

The code fix applies to a single-atom body, such as (a+)+ or (a*)*. A multi-atom body has no language-preserving rewrite that clears the diagnostic, so no fix is offered for that shape.

E128016: DateTime.Parse roundtrip

Flags DateTime.Parse and DateTime.ParseExact calls missing a DateTimeStyles parameter. Without DateTimeStyles.RoundtripKind, parsing an ISO 8601 UTC string silently converts it to local time.

// Before (warns)
var dt = DateTime.Parse(isoString);

// After
var dt = DateTime.Parse(isoString, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind);

E128020: in modifier with mutable structs

Flags in on mutable (non-readonly) struct parameters. The compiler creates a hidden defensive copy on every member access, silently changing behavior.

// Before (warns)
void Process(in Batch<Activity> batch) { }

// After
void Process(Batch<Activity> batch) { }

E128023: Hardcoded /tmp path

Flags string literals equal to "/tmp" or starting with "/tmp/" (and Windows equivalents). Use Path.GetTempPath() for cross-platform compatibility.

// Before (warns)
var path = "/tmp/my-file.txt";

// After
var path = Path.Combine(Path.GetTempPath(), "my-file.txt");

E128028: Task.FromResult wrapping sync I/O

Flags methods that return Task.FromResult or ValueTask.FromResult while also calling synchronous I/O methods that have async equivalents (e.g., File.ReadAllText instead of File.ReadAllTextAsync). Does not flag early-return guards, null-object implementations, or methods that already use await. The rule stays silent when the target framework has no async member for the pair, for example File.ReadAllTextAsync on netstandard2.0.

// Before (warns)
public Task<string> ReadConfig(string path)
{
    var content = File.ReadAllText(path);
    return Task.FromResult(content);
}

// After
public async Task<string> ReadConfig(string path)
{
    return await File.ReadAllTextAsync(path);
}

E128031: Disposable singleton factory

Flags AddSingleton factory registrations that return types implementing IDisposable. The DI container does not dispose singletons created via factory delegates — disposal must be handled manually or the registration restructured.

E128033: Options class with init-only properties

Flags options classes bound via Bind(...) or BindConfiguration(...) that have init-only properties. The analyzer resolves the OptionsBuilder<T> receiver type, so the extension-method form and the conditional-access form both report. The rule enforces a convention: options types bound from configuration keep mutable set accessors, so post-configure code, tests, and reload handlers can assign properties after construction. The report states the convention and does not claim a binder failure.

E128034: Constructor newing a DI-registered type

Flags constructors that new up a type that is registered in the DI container elsewhere. Inject the dependency instead of creating it directly.

E128035: Concrete-type DI dependency

Flags constructor parameters typed as concrete classes (not interfaces) that have no direct DI registration. The dependency should be registered and injected via its interface.

E128037: Unbounded Task.WhenAll

Flags Task.WhenAll(items.Select(async ...)) where the collection is unbounded. This fans out unlimited concurrent operations. Use Parallel.ForEachAsync or batch with a SemaphoreSlim.

The rule also flags a Task.Run call added to a task list inside a loop, then awaited with Task.WhenAll. That is the same unbounded fan-out with a different syntax. A SemaphoreSlim.WaitAsync throttle in the Task.Run lambda clears the report. A Task.WaitAsync timeout does not. A loop with a compile-time constant bound clears the report, because its fan-out is bounded.

E128038: Task.WhenAll missing CancellationToken

Flags Task.WhenAll async lambdas that capture a CancellationToken in scope but don’t pass it to the inner async calls. Cancellation won’t propagate.

E128039: Catch filter excluding OCE

Flags catch (Exception ex) when (...) filters that don’t exclude OperationCanceledException. Swallowing OCE prevents proper cancellation propagation.

E128040: Concurrency limit must be positive

Flags a negative SemaphoreSlim initial count, and a MaxDegreeOfParallelism or a Channel.CreateBounded capacity of zero or negative. A zero SemaphoreSlim initial count is legal and stays silent.

E128041: JsonDocument.RootElement lifetime

Flags JsonDocument.RootElement returned or assigned to a field/variable that escapes the using scope. After disposal, the RootElement points to freed memory.

E128051: HttpClient missing OCE catch

Flags broad catch (Exception) blocks inside async methods that call HttpClient without a preceding catch (OperationCanceledException). Swallowing OCE prevents proper timeout/cancellation handling. The code fix inserts a catch (OperationCanceledException) { throw; } clause before the broad catch.

E128056: File existence check TOCTOU race condition

Flags file-read calls (e.g., File.ReadAllText, File.OpenRead, File.OpenText) that follow a FileInfo.Exists property check or a File.Exists(path) call without a try/catch guard. Another process may delete the file between the check and the read, causing an unhandled IOException.

The rule compares the guarded value by symbol. It reports a read only when the checked value names the same storage location. A call argument such as Path.Combine(dir, name) names no storage location, so it is not matched.

// Before (warns)
if (file.Exists)
    content = File.ReadAllText(file.FullName);  // race window

// After
try
{
    content = File.ReadAllText(file.FullName);
}
catch (IOException) { }

Catch IOException, not FileNotFoundException. An absent parent directory raises DirectoryNotFoundException, which FileNotFoundException does not cover.

// Wrong: misses the absent-directory case
try { content = File.ReadAllText(path); } catch (FileNotFoundException) { }

// Right: both types derive from IOException
try { content = File.ReadAllText(path); } catch (IOException) { }

E128057: Unprotected cleanup in finally block

Flags cleanup calls (File.Delete, Directory.Delete, Dispose, etc.) in finally blocks that are not wrapped in their own try/catch. An exception thrown during cleanup will replace the original exception, making the root cause invisible.

// Before (warns)
finally
{
    File.Delete(tempPath);  // exception here swallows the original
}

// After
finally
{
    try { File.Delete(tempPath); } catch (IOException) { }
}

E128064: Disk write-then-read round-trip

Flags file-I/O sequences that write to a path and then immediately read the same path back into memory in the same method body. Returning the in-memory source value avoids a needless disk round-trip and the associated race window where another process can modify the file between the write and the read. Covers File.WriteAllText/ReadAllText, File.WriteAllBytes/ReadAllBytes, File.WriteAllLines/ReadAllLines, their Async variants, AppendAllText and AppendAllLines, File.CreateText/AppendText/Create/OpenWrite, StreamWriter/StreamReader, FileStream (write intent vs. read intent), BinaryWriter/BinaryReader, the equivalent FileInfo instance methods, and opaque write-to-disk calls (methods whose name contains ToDisk, ToFile, SaveTo, WriteTo, or DownloadTo) whose result is subsequently passed to File.Read*. Cross-kind matches (text write → bytes read, or bytes write → text read) are wrapped by the code fix in Encoding.UTF8.GetBytes/GetString. Opaque write-to-disk matches fire the diagnostic but offer no code fix (no in-memory source to substitute).

// Before (warns)
File.WriteAllText(path, content);
return File.ReadAllText(path);

// After
File.WriteAllText(path, content);
return content;

E128070: Pool Rent() capacity guard

Flags Rent(arg) calls on pool types (@@SQCODE1@@, @@SQCODE2@@, or any type with "Pool" in the name) where the capacity argument is not bounded. Passing int.MaxValue or an unbounded variable causes an OOM crash. Guard with Math.Min(value, cap). The fix wraps the argument in Math.Min. The cap comes from the e128_pool_rent_max_capacity option, which defaults to 1,048,576.

// Before (warns)
var buf = ArrayPool<char>.Shared.Rent(length);

// After
var buf = ArrayPool<char>.Shared.Rent(Math.Min(length, maxCapacity));

E128076: Materialize QuerySelectorAll result before iterating

Flags a foreach over an AngleSharp QuerySelectorAll result that does not pass through ToList() or ToArray(). The loop also reports when it reads a local variable initialized from an unmaterialized call. A call inside a lambda in the initializer is not reported. The collection is live, so a DOM change inside the loop moves elements that the loop has not visited yet.

// Before (warns)
foreach (var row in document.QuerySelectorAll("tr"))
{
    row.Remove();
}

// After
foreach (var row in document.QuerySelectorAll("tr").ToList())
{
    row.Remove();
}

E128077: TextContent string match requires a preceding length guard

Flags a Contains, StartsWith, EndsWith, or Equals call on an AngleSharp TextContent value when the same && chain holds no length guard. A comparison against 100 or fewer characters counts anywhere in the chain. A comparison against more than 100 characters counts only when it comes before the match. TextContent covers every descendant node, so an ancestor element can match text that belongs to a child.

// Before (warns)
if (block.TextContent.Contains("cookie"))
{
    block.Remove();
}

// After
if (block.TextContent.Length < 200 && block.TextContent.Contains("cookie"))
{
    block.Remove();
}

E128078: GetAttribute("href") on element that does not carry href

Flags GetAttribute("href") when the receiver is a local variable set from QuerySelector or QuerySelectorAll with a literal selector. Only a, link, area, and base elements carry href. The call returns null on any other element.

// Before (warns)
var div = document.QuerySelector("div");
var href = div.GetAttribute("href");

// After
var link = document.QuerySelector("a");
var href = link.GetAttribute("href");

No code fix. Change the selector, or read a different attribute.

E128079: CompositeDetection with single generic ID selector lacks specificity

Flags a CompositeDetection built from a collection expression that holds one ResourceDetection branch with a bare CSS ID selector such as #content or #main. Such a selector matches unrelated sites. Add a domain or meta-tag branch, or a second resource branch.

// Before (warns)
var detection = new CompositeDetection([new ResourceDetection("#content")]);

// After
var detection = new CompositeDetection(
[
    new DomainDetection("example.com"),
    new ResourceDetection("#content")
]);

No code fix.

E128086: ArrayPool buffer without SqliteParameter.Size

Flags ArrayPool<byte>.Shared.Rent() buffers passed as SqliteParameter values without an explicit .Size assignment. Rent() returns a buffer with Length >= requested, so without .Size SQLite reads the full oversized buffer, writing garbage bytes into the BLOB column.

// Before (warns)
var buf = ArrayPool<byte>.Shared.Rent(dataLength);
// ... fill buf[0..dataLength]
cmd.Parameters.AddWithValue("@data", buf);  // reads full oversized buffer

// After
var buf = ArrayPool<byte>.Shared.Rent(dataLength);
// ... fill buf[0..dataLength]
var param = new SqliteParameter("@data", buf) { Size = dataLength };
cmd.Parameters.Add(param);

The code fix sets Size to the length passed to Rent when that length is a literal or a plain identifier. It offers no fix when the code does not show the length.

E128089: Bare .Parse() without TryParse

Flags .Parse(...) calls on types that also expose a static TryParse method (e.g., int, double, DateTime, Guid, Enum). Parse throws FormatException on invalid input; TryParse lets callers handle failure without exceptions. No code fix — the failure-handling branch is context-specific.

// Before (warns)
var value = int.Parse(input);

// After
if (!int.TryParse(input, out var value)) { /* handle invalid input */ }

E128092: Sync File I/O with an async sibling

Flags a synchronous System.IO.File.* call (ReadAllText, WriteAllBytes, etc.) that has an Async sibling, when the containing method/local function/lambda is not already async. CA1849/VSTHRD103 only fire inside an already-async method; this rule also catches the fully-synchronous case, where those analyzers give no signal at all.

// Before (warns)
void Save(string path, string text)
{
    File.WriteAllText(path, text);
}

// After
async Task Save(string path, string text)
{
    await File.WriteAllTextAsync(path, text);
}

E128093: Sync DbConnection/DbCommand call with an async sibling

Flags a synchronous DbConnection/DbCommand call (Open, ExecuteReader, ExecuteNonQuery, ExecuteScalar, etc.) that has an Async sibling, when the containing method is not already async. Resolves the sibling through the base-type chain, so it also fires on provider subclasses that override the sync method but inherit the async one unchanged (e.g. @@SQCODE8@@'s @@SQCODE9@@/@@SQCODE10@@).

// Before (warns)
void Insert(SqliteConnection connection, FileInsertData data)
{
    using var command = connection.CreateCommand();
    command.ExecuteNonQuery();
}

// After
async Task Insert(SqliteConnection connection, FileInsertData data)
{
    using var command = connection.CreateCommand();
    await command.ExecuteNonQueryAsync();
}

E128096: Call async local function with await instead of blocking

Flags .Result or .Wait() on a call to a local function declared async. VSTHRD002 covers async methods but not local functions. The rule skips a call site that is already inside an async method or an async local function.

// Before (warns)
async Task<int> FetchAsync() => await GetValueAsync();
int value = FetchAsync().Result;

// After
int value = await FetchAsync();

E128099: Wait for process exit with a provable timeout

Flags Process.WaitForExit() and Process.WaitForExitAsync() with no argument. Also flags a single-token WaitForExitAsync(token) when the token is an enclosing method parameter or CancellationToken.None. A token from a CancellationTokenSource local counts as timeout-backed.

// Before (warns)
process.WaitForExit();

// After
if (!process.WaitForExit(TimeSpan.FromSeconds(30)))
{
    process.Kill();
}

E128100: Catch filter reads negated token state on OperationCanceledException

Flags a when filter of the form !token.IsCancellationRequested on a catch clause for OperationCanceledException or TaskCanceledException. The token state read races with the throw, so the filter can swallow a real cancellation. Rethrow without a filter instead.

// Before (warns)
catch (OperationCanceledException) when (!token.IsCancellationRequested)
{
    return Result.Failed;
}

// After
catch (OperationCanceledException)
{
    throw;
}

E128101: Verify process output file exists before use

Flags File.ReadAllText, ReadAllBytes, ReadAllLines, OpenRead, Open, OpenText, and the async forms when the call follows Process.WaitForExit or Process.WaitForExitAsync in the same method. An earlier File.Exists or FileInfo.Exists check for the same path suppresses the report. A failed binary or a wrong flag leaves the output missing.

// Before (warns)
process.WaitForExit();
var report = File.ReadAllText(outputFile);

// After
process.WaitForExit();
if (!File.Exists(outputFile))
{
    throw new InvalidOperationException("The process did not write the output file.");
}
var report = File.ReadAllText(outputFile);

E128103: DI resolve or named HttpClient resolve with no registration

Flags GetRequiredService<T>() and constructor parameters of registered types when no Add* or TryAdd* call in the same compilation registers the type. The rule reports at compilation end. GetService<T>() is not flagged, because it returns null on a miss.

Registration in another assembly needs an entry in the e128_registered_services option. The option holds comma-separated simple type names. Framework services such as ILogger, IHttpClientFactory, and IConfiguration need no entry. An open-generic registration matches by name.

The rule also flags IHttpClientFactory.CreateClient(name) when no AddHttpClient(name, ...) call in the compilation registers that name. An empty name and the unnamed overload are skipped, because both select the default client. A non-constant name is skipped. The rule reports one diagnostic per name, at the first use. No code fix.

// Before (warns)
services.AddHttpClient("billing", client => client.BaseAddress = billingUri);
var http = factory.CreateClient("bililng");

// After
services.AddHttpClient("billing", client => client.BaseAddress = billingUri);
var http = factory.CreateClient("billing");

E128109: stackalloc safety

Flags stackalloc inside a loop, with a size above 1024 bytes, or with a length that has no guard, or that is assigned to a pointer instead of Span<T>. Stack space is not reclaimed until the method returns. A conditional expression or an if statement counts as a guard only when its condition caps the whole length expression at 1024 bytes or less. Math.Min counts only when one argument is a constant at or under the cap. The size of an enum, a pointer, nint, nuint, and a struct made of known fields counts at its real width. The code fix assigns the buffer to Span<T> when the pointer is only indexed. The 1024-byte cap counts one frame only. Lower the cap in a method that recurses, because every frame keeps its own buffer.

// Before (warns)
Span<byte> buffer = stackalloc byte[length];

// After
Span<byte> buffer = length <= 256 ? stackalloc byte[length] : new byte[length];

E128110: Zero a pooled buffer before Return

Flags ArrayPool<T>.Return(buffer) unless the same finally block first calls CryptographicOperations.ZeroMemory on the whole rented array as a direct statement. A call nested in an if, loop, or lambda does not count. A slice such as buffer.AsSpan(0, used) does not satisfy the rule. Return(buffer, clearArray: true) does not satisfy it either. The rule covers ArrayPool<T> only. MemoryPool<T> is not checked. The fix inserts the CryptographicOperations.ZeroMemory call before the flagged Return inside its finally block. It offers no fix when the Return has no enclosing finally.

// Before (warns)
ArrayPool<byte>.Shared.Return(buffer);

// After
try { /* use buffer */ }
finally
{
    CryptographicOperations.ZeroMemory(buffer);
    ArrayPool<byte>.Shared.Return(buffer);
}

E128111: Pooled buffer used after Return

Flags a read or write of a rented buffer in a statement that follows ArrayPool<T>.Return(buffer). After Return the pool may give the array to another caller. Return from a finally block only when no other thread or pending async operation still uses the buffer. A reassignment of the buffer stops the scan. No code fix.

E128154: Singleton service depends on a scoped service

Flags an AddSingleton registration whose implementation type takes a constructor parameter of a type that an AddScoped call registers in the same compilation. The rule also reads TryAddSingleton, TryAddScoped, AddKeyedSingleton, AddKeyedScoped, AddHostedService<T>, and the typeof(...) overloads. The container builds the singleton once, so it keeps the first scoped instance for the life of the application. The rule reads a direct constructor dependency only. A parameter typed IServiceProvider, IServiceScopeFactory, or IServiceScope is not reported. A registration with a factory or an instance argument is not reported, because the container then receives a built instance or picks the constructor at run time. A service key argument does not count as such an argument.

// Before (warns)
services.AddScoped<Repository>();
services.AddSingleton<Worker>();

// After
services.AddScoped<Repository>();
services.AddScoped<Worker>();

The rule also carries a second descriptor on the same id. Flags a Microsoft.EntityFrameworkCore.DbContext registered through AddSingleton, TryAddSingleton, AddKeyedSingleton, or a typeof(...) overload. The rule also flags AddDbContext<T> or AddDbContextPool<T> with a constant ServiceLifetime.Singleton lifetime. A DbContext tracks every entity it materializes, so a singleton context keeps those entities for the life of the application and shares them across requests. The default AddDbContext<T>() registration stays silent, because it registers the context as scoped. A lifetime held in a variable or a parameter is not reported. The rule stays off when EF Core is absent from the compilation.

// Before (warns)
services.AddSingleton<AppDbContext>();

// After
services.AddDbContext<AppDbContext>();

E128155: Mutating the loop source inside its own foreach

Flags a call in a foreach body that mutates the collection the loop enumerates. The rule reads a local, a field, or a parameter as the loop source. A mutating call includes Add, AddRange, Clear, Insert, Remove, RemoveAt, RemoveAll, RemoveRange, Reverse, and Sort. An assignment to an index of a non-array collection is reported too, but an array element write is not. A mutation directly followed by break or return in the same block is not reported. The enumerator throws InvalidOperationException on the next step. An immutable, frozen, or concurrent collection is not reported. A mutation inside a lambda or a local function is not reported, because it runs after the loop. The report sits on the loop source, so one loop reports once. The code fix materializes the source with ToArray().

// Before (warns)
foreach (var item in items)
{
    items.Add(item);
}

// After
foreach (var item in items.ToArray())
{
    items.Add(item);
}

E128159: TaskCompletionSource without RunContinuationsAsynchronously

Flags a TaskCompletionSource creation that omits TaskCreationOptions.RunContinuationsAsynchronously. Without the flag, the awaiting continuation runs inside the thread that calls SetResult. That thread then runs foreign code, which can deadlock or stall a pool thread. A computed options value is not reported, because the rule cannot decide it. The code fix adds the flag, or combines it with an existing value by |. A TaskContinuationOptions argument binds to the state parameter, so the fix replaces it with the TaskCreationOptions flag.

// Before (warns)
var source = new TaskCompletionSource<int>();

// After
var source = new TaskCompletionSource<int>(TaskCreationOptions.RunContinuationsAsynchronously);

The rule reports a second shape. A SetResult, SetException, or SetCanceled call on a source stored in a field throws InvalidOperationException when a second caller completes the same source. A local, a parameter, a property, and a method result are not reported, because the rule cannot prove the source is shared. The safe forms TrySetResult, TrySetException, and TrySetCanceled return false instead of throwing.

// Before (warns)
private readonly TaskCompletionSource<int> source = new(TaskCreationOptions.RunContinuationsAsynchronously);

void Complete() => source.SetResult(1);

// After
void Complete() => source.TrySetResult(1);

E128161: Path.Combine with a rooted or parent segment

Flags a System.IO.Path.Combine call with a constant segment that starts from a root or climbs to a parent directory. A rooted segment drops every earlier segment, so the result escapes the base directory. The message for a rooted segment advises Path.Join. The message for a parent segment advises Path.GetFullPath on the result, then a check that it starts with the base directory, because Path.Join keeps .. and does not stop traversal. The rule reads both separators and the drive-letter form. A multi-part segment is reported when its .. parts climb above its start, so "a/../../b" is reported and "a/../b" is not. A segment that is exactly ".." is not reported, because a caller uses it on purpose. The code fix replaces the call with Path.Join for a rooted segment only. A parent segment still escapes under Path.Join, so a report on that shape offers no fix.

// Before (warns)
var path = Path.Combine("base", "/etc/passwd");

// After
var path = Path.Join("base", "/etc/passwd");

E128162: Local used after an explicit Dispose

Flags a member call on a local after the same block calls Dispose() on it. The Dispose() statement must sit directly in the block. A Dispose() in a braceless if, else, loop, or switch section is not reported, and neither is a read in a branch that excludes the Dispose(). A nameof(a), a is null, and a == null are not reads. The object throws ObjectDisposedException on the next member call that reads its state. A second Dispose call is not reported. An assignment to the local ends the disposed state, so the reads that follow are not reported. A dispose at the end of a using scope is not reported. A read inside a nested lambda or local function is not reported, because the block order does not give the time that body runs.

// Before (warns)
var stream = new MemoryStream();
stream.Dispose();
stream.WriteByte(1);

// After
var stream = new MemoryStream();
stream.WriteByte(1);
stream.Dispose();

E128163: ImmutableArray field left at its default

Flags an ImmutableArray<T> field that no initializer and no assignment reaches. The field keeps its default value, and the default array holds a null inner array. Every operation that reads it throws NullReferenceException. The rule collects assignments across the whole compilation, including a deconstruction, a ref or out argument, and an ImmutableInterlocked call, so a partial type that assigns the field in another file is not reported. The code fix initializes the field to ImmutableArray<T>.Empty.

// Before (warns)
private ImmutableArray<int> values;

// After
private ImmutableArray<int> values = ImmutableArray<int>.Empty;

E128170: Split(...)[n] index with no length guard

Flags a constant index of 1 or more taken from the result of string.Split. The array comes from an inline call or from a local initialized by one. Split returns one element when the separator is absent, so the index throws IndexOutOfRangeException on unexpected input. Index 0 and a from-end index such as [^1] are safe and not reported. A local is not reported when the same member reads Length on it before the index access. A Length read after the access does not count. The rule does not model control flow, so any earlier read counts as a guard, even one in a different branch. The rule does not track a Split result held in a field or a property, or one taken apart by deconstruction. A Split method on another type is not reported. No code fix.

// Before (warns)
var value = line.Split(':')[1];

// After
var parts = line.Split(':');
var value = parts.Length > 1 ? parts[1] : null;

E128171: Committed Assert.Fail red-phase stub

Flags an xUnit [Fact] or [Theory] whose only statement is a call to Xunit.Assert.Fail. The method can use a block body or an expression body. A Fail call after other assertions, and a Fail call in a method with no test attribute, are not reported. The stub marks unfinished work, so write the real assertions or remove the test before you commit. No code fix.

// Before (warns)
[Fact]
public void ParsesEmptyInput() => Assert.Fail("RED");

// After
[Fact]
public void ParsesEmptyInput() => Assert.Empty(Parser.Parse(string.Empty));

E128172: catch swallows an assertion failure

Flags a catch clause when its try block calls Xunit.Assert and the clause catches Exception, XunitException, or nothing in particular, and holds no throw. A failed assertion throws, so the catch turns a failing test into a passing one. A narrow exception type, such as InvalidOperationException, is not reported. A catch with a when filter is not reported. A catch that calls Assert.Fail is not reported. A throw inside a lambda or a local function does not count as a rethrow.

The code fix unwraps the try/catch and keeps the try statements, so the assertion failure surfaces. It applies only when the catch body is empty apart from whitespace. A catch with a body keeps the manual decision between rethrow, log, and narrowing. It declines a try whose only catch sits in a braceless body, because removing that handler would leave a try with no catch and no finally. Fix All unwraps every reported clause.

// Before (warns)
try { Assert.Equal(1, value); }
catch (Exception) { }

// After
Assert.Equal(1, value);

E128173: [SuppressMessage] or [ExcludeFromCodeCoverage] with no justification

Flags System.Diagnostics.CodeAnalysis.SuppressMessageAttribute and ExcludeFromCodeCoverageAttribute when the Justification argument is missing, null, empty, or blank. The rule skips ExcludeFromCodeCoverageAttribute on a target framework where the attribute has no Justification property, which is any framework before .NET 5. A reader needs the reason in the attribute to review or remove the suppression. A suppression still needs approval under the repository rules. No code fix.

// Before (warns)
[SuppressMessage("Design", "CA1000")]

// After
[SuppressMessage("Design", "CA1000", Justification = "The factory shape is part of the public API.")]

E128174: Constructor past the e128_max_ctor_dependencies ceiling

Flags a constructor, or a class or struct primary constructor, that takes more dependencies than the ceiling. A parameter counts as a dependency when its type is a service-like class or interface. Values, enums, delegates, arrays (including a params array), string, object, Uri, exceptions, record types, and collection types such as IReadOnlyList<T> and List<T> do not count. The default ceiling is 7. Set e128_max_ctor_dependencies in .editorconfig to change it. A record primary constructor is not checked. No code fix.

# .editorconfig
e128_max_ctor_dependencies = 5

E128175: SemaphoreSlim wait with no finally release guarantee

Flags a SemaphoreSlim.Wait or WaitAsync call that no later try/finally pairs with a Release call on the same semaphore. An exception between the wait and the release leaves the permit held. The rule reads the plain overloads only. A timeout overload supports the try-acquire shape, where no permit is held on the false path, so the rule skips it. The rule stays silent when an enclosing try already releases.

Code fix wraps the statements after the wait in a try block and adds Release in finally. It declines a goto that crosses the wrapped region.

// Before (warns)
await _sem.WaitAsync();
await WorkAsync();

// After
await _sem.WaitAsync();
try
{
    await WorkAsync();
}
finally
{
    _sem.Release();
}

E128176: Event subscription that keeps the subscriber alive

Flags an event subscription in a disposable type where the handler reads the subscriber instance and no dispose method removes the same event. The publisher holds the delegate, and the delegate holds the subscriber, so the subscriber stays reachable after its owner drops it. A handler that reads only a parameter or a local does not keep the subscriber alive, so the rule skips it. A static handler is skipped for the same reason. A subscription to an event on this instance is skipped, because the publisher dies with the subscriber. So is a subscription to an event on an instance field that Dispose, DisposeAsync, or DisposeAsyncCore disposes. Any -= on the same event inside Dispose, DisposeAsync, or DisposeAsyncCore clears the report. The rule does not compare the handler expression.

The code fix appends publisher.Event -= handler; to every declared Dispose, DisposeAsync, and DisposeAsyncCore method. The removal is idempotent, so appending to every dispose method is safe. It declines a lambda handler, a static-field publisher, and a type with no declared dispose method.

// Before (warns)
_publisher.Changed += (s, e) => _count++;

// After
_publisher.Changed += OnChanged;

public void Dispose() => _publisher.Changed -= OnChanged;

E128177: Record member with a mutable collection type

Flags a record member whose type is a mutable collection, such as List<T>, Dictionary<K,V>, HashSet<T>, ICollection<T>, IList<T>, or an array. The generated equality compares that member by reference, so two records with equal contents compare unequal. A record that declares its own GetHashCode is skipped, because it owns its equality. The rule reads a positional parameter, an auto-property, and a field, because all three join the generated equality. An immutable collection, an abstract property, a computed property, a static member, and a const field are skipped. Both a record class and a record struct are checked. No code fix.

// Before (warns)
public record Order(List<int> Lines);

// After
public record Order(ImmutableArray<int> Lines);

E128178: Duplicate JsonPropertyName value

Flags two members of one type that carry the same [JsonPropertyName] value, including a collision between a member on the derived type and one it inherits. System.Text.Json throws InvalidOperationException at the first serialize or deserialize call, so the failure lands far from the declaration. The rule matches the attribute by symbol, so a lookalike attribute never triggers it. An ignored member, an indexer, a static member, a member that is not public and has no [JsonInclude], and a member that overrides or hides the base member are skipped. A [JsonIgnore] with a condition other than Always keeps the member in the contract. The whole rule stays off when System.Text.Json is absent from the compilation. No code fix.

// Before (warns on the second member)
[JsonPropertyName("id")] public int Id { get; init; }
[JsonPropertyName("id")] public int Key { get; init; }

// After
[JsonPropertyName("id")] public int Id { get; init; }
[JsonPropertyName("key")] public int Key { get; init; }

E128179: Options type bound from configuration with no validation

Flags services.AddOptions<T>().Bind(...), AddOptions<T>().BindConfiguration(...), and services.Configure<T>(configuration) when the same chain carries no Validate, ValidateDataAnnotations, ValidateOnStart, or ValidateAllProperties call. A missing or malformed configuration value then reaches the consumer and fails at the point of use. A bare AddOptions<T>() and the Configure<T>(Action<T>) overload are skipped, because neither reads configuration. The rule matches the registration, the bind, and the validation through the option and DI extension symbols, so a user type with the same method name never triggers it. A separate services.AddSingleton<IValidateOptions<T>, ...> registration for the same options type clears the report.

The code fix appends .ValidateDataAnnotations().ValidateOnStart() to the chain. It registers only when the options type carries a DataAnnotations validation attribute and the compilation references the hosting extensions. A type with no attributes keeps the manual decision, because writing attributes invents caller policy.

// Before (warns)
services.AddOptions<RetryOptions>().Bind(configuration.GetSection("Retry"));

// After
services.AddOptions<RetryOptions>()
    .Bind(configuration.GetSection("Retry"))
    .ValidateDataAnnotations()
    .ValidateOnStart();

E128181: HttpClient.Timeout set to an infinite value

Flags an assignment of Timeout.InfiniteTimeSpan or TimeSpan.FromMilliseconds(-1) to HttpClient.Timeout. The request then never times out, so a stalled server blocks the caller and its thread pool slot. The assignment is reported in an object initializer, in a property assignment, and inside a ConfigureHttpClient lambda. A computed value is skipped, because the rule cannot prove it is infinite. No code fix.

// Before (warns)
client.Timeout = Timeout.InfiniteTimeSpan;

// After
client.Timeout = TimeSpan.FromSeconds(30);

E128182: IAsyncEnumerable value enumerated twice

Flags a second enumeration of one IAsyncEnumerable<T> value inside one method body. A second loop can re-run the source, and a single-pass source such as a channel reader yields nothing the second time. Enumerations in the two branches of one if are skipped, and an assignment to the value between two loops starts a new count. An inline-created sequence is skipped, because a factory call may return a fresh sequence. An iterator body that carries yield is skipped, because it hands items onward. No code fix.

// Before (warns)
await foreach (var row in rows) { Count(row); }
await foreach (var row in rows) { Store(row); }

// After
var materialized = await rows.ToListAsync();
foreach (var row in materialized) { Count(row); }
foreach (var row in materialized) { Store(row); }

E128183: Task.WhenAny result is never awaited

Flags a Task.WhenAny call whose result is discarded or stored in a local that the enclosing block never reads. The returned task never completes faulted, so a fault in every task in the set stays unobserved. An awaited, returned, yielded, stored, or passed result is skipped, because the caller may observe it there. A WhenAny declared on another type is skipped. No code fix.

// Before (warns)
Task.WhenAny(first, second);

// After
var winner = await Task.WhenAny(first, second);
await winner;

E128186: await inside a finally block

Flags an await expression in the body of a finally clause. The awaited call runs while the original exception propagates, so a fault there replaces the original failure. await using and await foreach count too, and the report sits on the await keyword. An await in a try block or a catch clause is skipped. An await in a local function or a lambda declared in the finally body is skipped. An await inside a nested try is skipped, and an await inside a nested finally reports once, at the inner clause. No code fix.

// Before (warns)
finally
{
    await flushing.DisposeAsync();
}

// After
try
{
    await flushing.FlushAsync();
}
finally
{
    flushing.Dispose();
}

E128188: Exception filter reads the message text

Flags a when filter that reads Message, StackTrace, or ToString on the caught exception. The filter runs before any catch clause, so a formatted member costs work on the fault path and can throw inside the filter itself. A filter that reads HResult or InnerException is skipped. A read on another object, a method call such as ex.GetType(), and a catch clause with no variable are skipped. The rule binds the receiver to the catch variable by symbol, so a lambda parameter or a local with the same name is skipped. No code fix.

// Before (warns)
catch (HttpRequestException ex) when (ex.Message.Contains("timeout", StringComparison.Ordinal))
{
    retry = true;
}

// After
catch (HttpRequestException ex) when (ex.InnerException is TimeoutException)
{
    retry = true;
}

E128189: GCHandle with no Free call

Flags a local that stores a GCHandle.Alloc result in the same body and never calls Free on it. The handle pins the target object, so a missing Free keeps the object reachable and pinned. The rule also reads a later assignment to the same local. A local passed to a method, returned, or stored in a field, a property, another local, or a collection is not reported, because it may leave the method. An allocation assigned directly to a field or an element, and a discarded allocation, are not reported. A bare Alloc(x) call that binds through using static is read as well. The rule stops when GCHandle is absent from the compilation or resolves to a user type.

Code fix wraps the statements after Alloc in a try block and adds Free in finally. It declines a goto that crosses the wrapped region.

// Before (warns)
var handle = GCHandle.Alloc(payload, GCHandleType.Pinned);
IntPtr address = handle.AddrOfPinnedObject();

// After
var handle = GCHandle.Alloc(payload, GCHandleType.Pinned);
try
{
    IntPtr address = handle.AddrOfPinnedObject();
}
finally
{
    handle.Free();
}

E128190: FileStream created without asynchronous I/O

Flags a FileStream construction that cannot run asynchronous I/O. The call passes useAsync: false or a FileOptions value with no FileOptions.Asynchronous bit. A constructor that has neither parameter, such as new FileStream(path, mode, access, share), is not reported. An async read then runs as blocking work on a pool thread. A useAsync value of true, an options value with FileOptions.Asynchronous, and a non-constant argument are skipped. The SafeFileHandle overload has no asynchronous switch, so the rule skips it. A user type named FileStream is skipped.

The code fix flips the useAsync argument to true, ors FileOptions.Asynchronous into the options value, and appends a named useAsync: true argument when the parameter is absent. It registers only when the member awaits an asynchronous call on the same stream local. It declines a creation that is not assigned to a local.

// Before (warns)
using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, false);

// After
using var stream = new FileStream(
    path,
    FileMode.Open,
    FileAccess.Read,
    FileShare.Read,
    bufferSize: 4096,
    useAsync: true);

E128192: GetBuffer on a MemoryStream with a hidden buffer

Flags a MemoryStream.GetBuffer() call whose receiver was created from a byte[] without publiclyVisible: true. The call throws UnauthorizedAccessException for such a stream. The empty and capacity constructors expose the buffer, so the rule skips them. The rule follows a local to its creation in the same body, and a parameter to an in-body assignment. A stream created with publiclyVisible: true, a non-constant flag, and a receiver that is a field, a property, or a method result are skipped. No code fix.

// Before (warns)
var buffer = new MemoryStream(new byte[8]);
byte[] raw = buffer.GetBuffer();

// After
var buffer = new MemoryStream(new byte[8]);
byte[] raw = buffer.ToArray();

E128193: Disposable field overwritten in a loop without a dispose

Flags an assignment to a field whose type implements IDisposable or IAsyncDisposable inside a loop body, when no earlier dispose call on the same field appears inside the same loop. A field whose type is a type parameter with an IDisposable constraint counts as disposable. The overwritten instance keeps its unmanaged resources until the finalizer runs. A dispose call on the same field before the assignment, inside the same loop, clears the report, including field?.Dispose() and this.field?.Dispose(). The suppression requires a dispose inside the same loop. A dispose before the loop, or anywhere outside the loop body, does not clear the report. A local, a parameter, a property, a compound assignment, a value type, and an assignment outside a loop are skipped. No code fix.

// Before (warns)
foreach (var item in items)
{
    _current = new Subscription(item);
}

// After
foreach (var item in items)
{
    _current?.Dispose();
    _current = new Subscription(item);
}

E128194: Lazy<T> field without thread safety

Flags a Lazy<T> field whose initializer passes LazyThreadSafetyMode.None. Two threads can then build the value twice, and each caller gets a different instance. The Lazy<T>(factory, false) overload means the same thing and is reported too. An omitted mode, ExecutionAndPublication, PublicationOnly, and a non-constant mode are skipped, because the default is thread safe. The rule reads a field declarator only, so a local, a parameter, and a property initializer are skipped. A user type named Lazy<T> is skipped.

The code fix removes the LazyThreadSafetyMode.None argument, or the isThreadSafe: false argument, so the constructor uses its thread-safe default. It binds the argument by constructor parameter, so a positional and a named form both match.

// Before (warns)
private static readonly Lazy<Cache> Shared =
    new(() => new Cache(), LazyThreadSafetyMode.None);

// After
private static readonly Lazy<Cache> Shared = new(() => new Cache());

E128195: Configuration key absent from the appsettings files

Flags a constant configuration key that no appsettings*.json additional file defines. The rule reads only those files, and a file that fails to parse is skipped. The rule reads the key from an IConfiguration indexer, from GetSection or GetRequiredSection, and from GetConnectionString, which maps to ConnectionStrings:<name>. A section read needs the section prefix, not a leaf. A read through an IConfigurationSection is relative to that section, and an indexer assignment defines a key, so the rule skips both. The JSON reader accepts comments and trailing commas. A key comparison ignores case, because the configuration provider ignores case. A non-constant key and a receiver that is not an IConfiguration are skipped. The rule stays off when the project passes no parsable appsettings*.json additional file.

The project must pass the file in. A key from an environment variable, a user secret, or a file outside the project is not visible to the rule.

<ItemGroup>
  <AdditionalFiles Include="appsettings.json" />
</ItemGroup>

A key that a run-time source supplies needs an entry in the e128_added_configuration_keys option. The option holds comma-separated keys and adds them on top of the parsed files. The option never activates the rule on its own.

# .editorconfig
e128_added_configuration_keys = FeatureFlags:Beta, External:Endpoint
// Before (warns when no appsettings file defines the key)
var level = configuration["Logging:LogLevel:Default"];

// After
var level = configuration.GetRequiredSection("Logging:LogLevel")["Default"];

E128196: JsonSerializerOptions mutated after first use

Flags a write to a JsonSerializerOptions member after the same method body passes the instance to JsonSerializer.Serialize or JsonSerializer.Deserialize. The serializer freezes the instance on first use, so the next write to WriteIndented, PropertyNamingPolicy, a converter, or any other member throws InvalidOperationException. A write before the first call is not reported, and a write to an instance that the body never uses is not reported. The rule reads a local, a parameter, and a field. A serializer call inside a lambda or a local function, and a call in the other branch of the same if, do not count as an earlier use. Assigning a new instance to the same variable between the call and the write resets the check. A property receiver is skipped, because the getter can return a new instance on each read. A use in one method and a write in another method stay silent, because the rule reads one body at a time.

// Before (warns)
var options = new JsonSerializerOptions();
var json = JsonSerializer.Serialize(value, options);
options.WriteIndented = true;

// After
var options = new JsonSerializerOptions { WriteIndented = true };
var json = JsonSerializer.Serialize(value, options);

E128197: Fixed day count used as a calendar month

Flags a TimeSpan.FromDays(28) to TimeSpan.FromDays(31) call added to or subtracted from a DateTime or a DateTimeOffset. The span stands in for a calendar month, and a calendar month holds 28 to 31 days, so the result drifts from the calendar. The rule reads the Add and Subtract methods, the + and - operators, and the += and -= assignments. The severity is Info, because a 30-day span is often a fixed retention window. It reads an inline call with a constant argument only. A span held in a variable, a constant field, or a computed value is not reported, because the rule cannot tell a month from a 30 day window. DateTime.AddDays(30) is not reported either, because the caller asked for days.

// Before (warns)
var due = today.Add(TimeSpan.FromDays(30));

// After
var due = today.AddMonths(1);

E128198: Substring count built from a length minus a constant

Flags a two-argument string.Substring call whose count is a Length value minus a positive constant. A string shorter than the constant makes the count negative, and the call throws ArgumentOutOfRangeException. The count shapes are Length - k, Length - start - k, and the same forms in parentheses. A length test on the same string in an enclosing if condition or conditional expression clears the report. So does a preceding if with no else that returns, throws, continues, or breaks after a length test on the same string. A plain comparison decides the branch: Length > k guards the then branch, and Length < k guards the else branch. The rule reads one call site, so a guard in a caller method does not clear it. A subtraction whose right side is a variable is not reported, because a start index that IndexOf returns needs its own check.

// Before (warns)
var body = text.Substring(0, text.Length - 1);

// After
var body = text.Length > 0 ? text.Substring(0, text.Length - 1) : text;

E128234: A FileStream position is shared across parallel readers

Flags a FileStream that a Parallel.For, Parallel.ForEach, or Parallel.Invoke body captures. The stream keeps one file position, so parallel workers move that position at the same time and read the wrong bytes.

The rule resolves Parallel and FileStream by symbol, so user types with the same names stay silent. A stream opened inside the body is a per-worker stream and stays silent. The rule carries no code fix, because the remedy moves the read helper to File.OpenHandle and RandomAccess.Read at an explicit offset, and that change crosses a helper boundary.

// Before (warns)
using FileStream stream = File.OpenRead(path);
Parallel.ForEach(offsets, offset => ReadAt(stream, offset));

// After
using SafeFileHandle handle = File.OpenHandle(path, FileMode.Open, FileAccess.Read);
Parallel.ForEach(offsets, offset => RandomAccess.Read(handle, buffer, offset));

E128238: Array compared by reference

Flags ==, !=, and Equals on two single-rank arrays whose element type is not byte. The operators compare the array identity, so two arrays with equal contents never compare equal.

The fix rewrites the comparison to Enumerable.SequenceEqual and adds using System.Linq; when absent. An inequality becomes a negated call. The rule stays silent on a null test, on a multi-dimensional array, and on a byte[] sentinel check. A multi-dimensional array implements no generic sequence, so the fix cannot repair it.

// Before (warns)
if (left == right) { }

// After
if (Enumerable.SequenceEqual(left, right)) { }

E128239: Stream.Read count is discarded

Flags a Stream.Read call used as a statement when a later statement in the same block reads the buffer. A stream can return fewer bytes than the buffer length, so the later read consumes stale bytes.

The rule stays silent when the count is stored, when the buffer is not read later, and when the buffer is reassigned first. A lambda and a local function body stay out, because statement order does not describe when they run. The rule carries no code fix, because the correct count handling depends on the caller’s intent.

// Before (warns)
stream.Read(buffer, 0, buffer.Length);
Use(Encoding.UTF8.GetString(buffer));

// After
var read = stream.Read(buffer, 0, buffer.Length);
Use(Encoding.UTF8.GetString(buffer, 0, read));

E128240: Blocking call inside a lock

Flags Thread.Sleep, a File call, a blocking Stream member, and the synchronous DbCommand execute family inside a lock body. The lock stays held for the whole call.

A MemoryStream member stays silent because it completes without I/O. A nested lock reports its own calls, and a lambda or local function body stays out. The rule carries no code fix, because the remedy moves the work outside the lock, or switches to an asynchronous primitive.

// Before (warns)
lock (_gate)
{
    _cache = File.ReadAllText(path);
}

// After
var text = File.ReadAllText(path);
lock (_gate)
{
    _cache = text;
}

E128243: Span over a list invalidated by a later mutation

Flags a CollectionsMarshal.AsSpan(list) local that is read after a call which can reallocate the list. The old span points at memory the list no longer owns.

The rule reports the mutating call. It covers Add, AddRange, Clear, EnsureCapacity, Insert, InsertRange, Remove, RemoveAll, RemoveAt, RemoveRange, Reverse, Sort, TrimExcess, and CollectionsMarshal.SetCount. A read before the mutation, a mutation of another list, and an index assignment stay silent. The rule carries no code fix, because the span must be reacquired at the right point.

// Before (warns)
var span = CollectionsMarshal.AsSpan(list);
list.Add(value);
Use(span);

// After
list.Add(value);
var span = CollectionsMarshal.AsSpan(list);
Use(span);

E128244: Zero guard after the division

Flags a zero comparison on a divisor that an earlier statement already divided by. An integer or decimal divide by zero throws before the guard runs.

The rule covers ==, !=, integer division, modulo, and compound assignment. A guard before the division, a floating-point division, and a property divisor stay silent. The rule carries no code fix, because reordering the guard changes control flow.

// Before (warns)
var result = value / divisor;
if (divisor == 0) { return 0; }

// After
if (divisor == 0) { return 0; }
var result = value / divisor;

E128245: Enum cast outside the member set

Flags a constant integral-to-enum cast whose value matches no declared member. A runtime operand stays silent.

A [Flags] enum stays silent, because any bit combination is valid. An alias value stays silent. A test compilation stays silent, because a validator test builds an undefined value on purpose. The rule carries no code fix, because the intended member depends on intent.

enum Status { None = 0, Ready = 1, Busy = 2 }

// Before (warns)
var status = (Status)7;

// After
var status = Status.Ready;

E128246: Flags member value is not a power of two

Flags a [Flags] enum member with a multi-bit value that does not name its combination. A member should own one bit. ReadWrite and All name their combinations.

The rule stays silent on a zero or negative value, on a single-bit member, and on a non-flags enum. It carries no code fix, because the intended bit depends on intent.

[Flags]
enum Permission
{
    None = 0,
    Read = 1,
    Write = 2,
    Execute = 3   // warns
}

E128248: Floating-point loop counter

Flags a for loop whose counter is a float or double. A floating-point step accumulates representation error, so the terminal comparison can miss or overshoot.

The rule reads a declared counter, a counter assigned in the initializer, and a counter that appears only in the incrementor. A decimal counter stays silent. The rule carries no code fix, because an integer counter or a different termination condition depends on the loop.

// Before (warns)
for (double d = 0; d < 1; d += 0.1) { }

// After
for (var i = 0; i < 10; i++) { }

E128250: Dead store to a private field

Flags a simple assignment to a private field that a later statement in the same block overwrites before any read. The first value is never observable.

The rule clears its tracked writes at any call, object creation, or control-flow statement, because those can read the field or skip the next write. A read clears the field’s tracked write. The final write of a block stays silent, because the field lives after the method returns. A compound assignment and a field another type declares stay out.

The code fix deletes the dead store when its right side is a literal, an identifier, or a field access. A right side that reads a property or indexer can carry a side effect and keeps the manual decision.

// Before (warns)
_value = 1;
_value = 2;

// After
_value = 2;

E128251: Loop with no exit path

Flags while (true), for (;;), and do ... while (true) when the body has no local exit. A break that targets the loop, a return, a throw, a goto, and a yield break count. A break in a nested loop or switch targets the inner construct and does not count.

Environment.Exit, Environment.FailFast, and ThrowIfCancellationRequested also count. A lambda and a local function body stay out. The rule carries no code fix, because the intended exit condition or cancellation source belongs to the caller.

// Before (warns)
while (true)
{
    Work();
}

// After
while (!cancellationToken.IsCancellationRequested)
{
    Work();
}

E128258: Service lookup throws a generic exception with no key

Flags Enumerable.First and Enumerable.Single whose receiver is GetServices<T>() or GetKeyedServices<T>(key), directly or through Where. The static call form Enumerable.First(provider.GetServices<T>()) also reports. The failure reads Sequence contains no matching element and names no key. The rule suggests FirstOrDefault or SingleOrDefault plus an exception that names the missing service. No code fix, because the message needs the key.

E128260: Retained memory is read after its owner is disposed

Flags a Memory<T> local assigned from owner.Memory or owner.Memory.Slice(...) inside a using statement, then read after the statement ends. The owner returns its buffer on dispose, so the retained slice can read memory that another caller has reused. No code fix.

The rule reads the using form and a local declared before the statement. It stays silent when the read sits inside the using scope, when the owner is not an IMemoryOwner<T> or MemoryManager<T>, and when the local is overwritten with a fresh value (.ToArray(), default, a literal, or a creation expression) before the read. An out argument and a deconstruction count as writes.

E128269: Declaration syntax read without a syntax tree check

Flags a SyntaxReference.GetSyntax call on an element of ISymbol.DeclaringSyntaxReferences when a SemanticModel is in scope and the containing type never compares a tree (==, !=, is, Equals, ReferenceEquals, or GetSemanticModel). A GetSyntax result that only feeds an is type test stays silent. The element comes from a foreach variable, an index, First, or FirstOrDefault. A symbol that is not a local can declare itself in another file, and a SemanticModel method throws ArgumentException for a node from another tree. The throw shows as AD0001 in the consumer build. A local, parameter, or range variable symbol stays silent, and so does a method with no SemanticModel and no context that exposes one. The rule runs only in a compilation that references Microsoft.CodeAnalysis. The code fix inserts if (reference.SyntaxTree != model.SyntaxTree) { continue; } as the first statement of a foreach loop. It registers no fix when two model expressions are in scope or for the index, First, and FirstOrDefault shapes.

E128270: Rented pooled buffer is never returned

Flags a local variable assigned from ArrayPool<T>.Rent(...) when the containing member, local function, or lambda holds no pool Return call and no return of that variable. The rule reads a declared local only. An inline rent expression, a field assignment, and a custom pool type stay silent. A helper that returns the buffer stays silent only when the same scope also calls Return.

Code fix wraps the statements after Rent in a try block and zeroes and returns the buffer in finally. It emits CryptographicOperations.ZeroMemory only when the consumer compilation carries that type. It declines a goto that crosses the wrapped region.

// Warns: the buffer stays checked out
var buffer = ArrayPool<byte>.Shared.Rent(32);
buffer[0] = 1;

// Correct
var buffer = ArrayPool<byte>.Shared.Rent(32);
try
{
    buffer[0] = 1;
}
finally
{
    CryptographicOperations.ZeroMemory(buffer);
    ArrayPool<byte>.Shared.Return(buffer);
}