Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

CS0219: The Variable Is Assigned but Its Value Is Never Used

Roslyn reports CS0219 only for locals whose assigned value is dead and side-effect free. How to tell a leftover from a forgotten return, and where to suppress it.

~6 min readC#
#C##.NET#Compiler Warnings#Debugging
3D illustration of stacked code slabs with one detached amber slab and a warning triangle above it

Introduction & Quick Summary

Symptom. dotnet build prints warning CS0219: The variable 'retries' is assigned but its value is never used, or the IDE underlines a local with a yellow squiggle that survives every refactor. The build still succeeds, so it is easy to ignore for months — until CI turns warnings into errors and a variable somebody left behind blocks the team.

Cause. The compiler's definite-assignment and data-flow analysis proved that a local variable received a value that no later instruction reads. Roslyn reports CS0219 only for locals whose right-hand side is a compile-time constant or otherwise side-effect free, because deleting an assignment whose right-hand side calls a method would change program behaviour. Nothing is wrong with the emitted IL: the assignment is still compiled. The warning reports dead code, not a broken program.

Fix. Decide which of three situations you are in before editing the line. If the value is dead, delete the declaration. If the assignment keeps a call site or satisfies conditional compilation, state the intent with a discard (_ = value;) or a scoped #pragma warning disable CS0219. If the variable should have been read — a computed result never returned — the warning found a real bug, and the fix belongs in the logic, not in a suppression list.

Core Mechanics, Signatures & Reproducible Setup

CS0219 belongs to a family of unused-code diagnostics that look alike and mean different things. Flow analysis tracks each local from declaration to every read; a store no path reads is a dead store. Roslyn narrows the report so code with observable side effects is never flagged:

  • A local initialised with a constant (int x = 0;, string tag = "debug";) is reported.
  • A local initialised from a method call (var x = Compute();) is not reported, even when x is never read, because removing it would remove the call.
  • A field is reported as CS0414, not CS0219. Fields live across method calls and may be read through reflection or serialization, so the heuristic differs.

A minimal reproducer, using the SDK's warning output rather than an IDE:

csharp
// dotnet new console -o cs0219-demo && cd cs0219-demo // dotnet build -warnaserror:CS0219 static int ParseOrDefault(string raw) { int fallback = 42; // CS0219: assigned, never read if (int.TryParse(raw, out int parsed)) { return parsed; } return 0; // the bug: fallback was meant to be returned }

dotnet build reports one warning, and -warnaserror:CS0219 turns that one into an error while leaving the others alone.

To see which situations the compiler refuses to flag, compare the two methods below. The second one compiles clean even though cache is never read, because the right-hand side allocates and calls into ILogger:

csharp
static void FromConstant() { int attempts = 3; // CS0219 } static void FromCall(ILogger log) { var cache = new Dictionary<string, int>(); // no warning log.LogDebug("cache primed"); }

The distinction matters when you "fix" a warning: you cannot silence CS0219 by adding a side-effecting call, because that call removes the warning by itself — and the dead call now costs time on every execution.

Key Comparison Table

Diagnostic identity is the first thing to check, because the natural fix differs for each code.

DiagnosticEmitted forMessageTypical real cause
CS0219Local, constant initialiser, never readassigned but its value is never usedDebug leftover, forgotten return
CS0168Local declared, never assigned or readdeclared but never usedUnused out variable, stale parameter copy
CS0414Private field, assigned, never readassigned but its value is never usedLeftover flag, removed feature switch
CS0162Unreachable statementunreachable code detectedreturn before a block, while (false)
CS8321Local function never calleddeclared but never usedRefactor that inlined the call
IDE0059Local, any initialiser, never readunnecessary assignment of a valueStyle analyzer, not the compiler
IDE0051Private member never usedunused private memberDead API surface

IDE0059 is the one people confuse with CS0219: it comes from the .NET SDK analyzers, needs EnforceCodeStyleInBuild or a matching AnalysisLevel, covers method calls too, and is a suggestion by default. A repository can show IDE0059 in the editor and no CS0219 in dotnet build for the same line.

The suppression choices differ in scope and risk:

ApproachScopeCI effectRisk
Delete the lineFileWarning goneNone if the value was dead
_ = value; discardLineWarning gone, expression evaluatedHides the intent if the value was meaningful
#pragma warning disable CS0219 … restoreRegionWarning goneSuppression can outlive its reason
<NoWarn>0219</NoWarn> in .csprojProjectWarning gone everywhereHides new dead stores in all files
.editorconfig dotnet_diagnostic.CS0219.severityDirectoryConfigurable per treeSilently ignored by older tooling
-warnaserror:CS0219Build invocationWarning becomes an errorBlocks builds on legacy code until cleaned

Practical Edge Cases, Error Fixes & Deep Dive Code Examples

1. The debugging leftover

The most common origin is a variable added to inspect a value that the code now logs instead.

csharp
// Before: the temp was used with a breakpoint, the loop now logs foreach (var order in orders) { decimal total = order.Subtotal + order.Tax; // CS0219 log.LogInformation("order {Id} {Total}", order.Id, total); } // After: one expression, no dead store foreach (var order in orders) { log.LogInformation("order {Id} {Total}", order.Id, order.Subtotal + order.Tax); }

Deleting is correct: Subtotal + order.Tax is pure and the log call reads the same values.

2. Conditional compilation branches

A variable that exists for one configuration only warns on one build — exactly the noise that gets suppressed project-wide by accident.

csharp
static HttpClient Create() { #if DEBUG var handler = new LoggingHandler(); // CS0219 in Release builds that strip the next line #endif var client = new HttpClient(NewHandler()); return client; }

Keep the declaration inside the same #if block as its use, or move the whole construction into the region. Never blanket-disable CS0219 for one configuration.

3. A default that should have been returned

A default that is assigned and forgotten is a logic bug with a warning attached. Read this case twice: the compiler is telling you a branch returns something else.

csharp
// Before: fallback is dead, so every failure returns 0 int fallback = 42; if (int.TryParse(raw, out var parsed)) return parsed; return 0; // After: the intended fallback is used if (int.TryParse(raw, out var parsed)) return parsed; return 42;

4. out variables and tuple deconstruction

An out declaration that is never read is CS0168, not CS0219, and its fix is a discard — the idiomatic way to say the value is not needed:

csharp
// Reads only the key; the value slot is discarded if (map.TryGetValue(key, out _)) { // ... } // Deconstruction with discards var (_, lastError) = SplitResult(input);

_ is a discard only when no _ variable is in scope, so older files that declare int _ = 0; break the moment they also use out _.

5. Assignments that exist only to satisfy the flow analysis

Sometimes the value is genuinely unused but the assignment documents an invariant or is generated. A discard states the intent without lying to the analysis; never replace a dead store with GC.KeepAlive or an empty if, which silence the warning and add code readers must decode.

csharp
// Explicit: the expression is evaluated, the result is intentionally dropped _ = decimal.TryParse(input, out _); // Generated code: suppress locally, never for the project #pragma warning disable CS0219 // generated by the DTO builder var schemaVersion = 2; #pragma warning restore CS0219

6. Enforcing it in CI without breaking the build

Escalate to an error only after the code is clean, and scope it to the projects that are:

xml
<!-- Directory.Build.props in the cleaned subtree only --> <PropertyGroup> <WarningsAsErrors>$(WarningsAsErrors);CS0219;CS0168;CS0414</WarningsAsErrors> </PropertyGroup>

WarningsAsErrors extends the existing list instead of replacing it, so nullable warnings a project already escalates survive. Check on a branch first: -warnaserror on the command line overrides the project setting and surfaces every unrelated warning at once.

Common Compilation/Runtime Mistakes & Version Gotchas

  • Silencing project-wide what one file caused. <NoWarn>0219</NoWarn> applies to every current and future file. Delete the line, or scope the pragma around the generated region.
  • Expecting CS0219 for method calls. var x = SomeFactory(); never warns even when x is unused. Hunt those with IDE0059 or dotnet format --severity info.
  • Confusing the IDE with the compiler. IDE0059 is an analyzer suggestion; a clean dotnet build without EnforceCodeStyleInBuild says nothing about the editor.
  • Warning counts after a target-framework change. SDKs ship different analyzer versions, so the same source can warn in .NET 9 and stay silent in a netstandard2.0 library built by an older toolchain. Compare dotnet --version first.
  • Cleaning up in a finally. A dead store inside finally is still reported, and deleting it can reorder side effects on exception paths. Read the region, not the line.
  • Generated code reintroduces it. A source generator that emits dead stores warns on every build; suppress inside its file scope with a comment naming the generator, so the suppression can go when the generator is fixed.

Related tools. When you rewrite a method to remove dead stores, paste both versions into the text diff tool to confirm that only the intended lines changed, and use the JSON formatter when the value you were inspecting at a breakpoint is serialized configuration, so the before and after payloads can be compared structurally instead of by eye.

Try matching browser tools

All tools

Small utilities that fit C# work — they run entirely in this browser tab, so nothing you paste leaves your device.

All C# guides

More in C#

All C# guides

The guides filed next to this one in C#, in library order.