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.

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 whenxis 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:
// 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:
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.
| Diagnostic | Emitted for | Message | Typical real cause |
|---|---|---|---|
| CS0219 | Local, constant initialiser, never read | assigned but its value is never used | Debug leftover, forgotten return |
| CS0168 | Local declared, never assigned or read | declared but never used | Unused out variable, stale parameter copy |
| CS0414 | Private field, assigned, never read | assigned but its value is never used | Leftover flag, removed feature switch |
| CS0162 | Unreachable statement | unreachable code detected | return before a block, while (false) |
| CS8321 | Local function never called | declared but never used | Refactor that inlined the call |
| IDE0059 | Local, any initialiser, never read | unnecessary assignment of a value | Style analyzer, not the compiler |
| IDE0051 | Private member never used | unused private member | Dead 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:
| Approach | Scope | CI effect | Risk |
|---|---|---|---|
| Delete the line | File | Warning gone | None if the value was dead |
_ = value; discard | Line | Warning gone, expression evaluated | Hides the intent if the value was meaningful |
#pragma warning disable CS0219 … restore | Region | Warning gone | Suppression can outlive its reason |
<NoWarn>0219</NoWarn> in .csproj | Project | Warning gone everywhere | Hides new dead stores in all files |
.editorconfig dotnet_diagnostic.CS0219.severity | Directory | Configurable per tree | Silently ignored by older tooling |
-warnaserror:CS0219 | Build invocation | Warning becomes an error | Blocks 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.
// 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.
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.
// 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:
// 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.
// 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 CS02196. 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:
<!-- 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 whenxis unused. Hunt those with IDE0059 ordotnet format --severity info. - Confusing the IDE with the compiler. IDE0059 is an analyzer suggestion; a clean
dotnet buildwithoutEnforceCodeStyleInBuildsays 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 --versionfirst. - Cleaning up in a
finally. A dead store insidefinallyis 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 toolsSmall utilities that fit C# work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related C# guides
All C# guidesC# Dispose vs Destructor: Key Differences Explained
c# dispose vs destructor: Understand the difference between Dispose and destructors in C#, when each runs, and how to manage unmanaged resources correctly.
C# Variable Declaration: Syntax and Practical Usage
How to declare C# variables: type-then-name syntax, var vs explicit types, nullable annotations, default values, and block scope rules with examples.
C# Primary Constructors for Classes: Syntax and Usage
Learn how to use C# primary constructors for classes: syntax, initialization, dependency injection, and limitations with practical examples.
C# IComparer: Custom Sorting with IComparer<T>
Learn IComparer<T> in C# with a working example: custom sort order for Array.Sort and List<T>.Sort, null-safe Compare rules, and reuse tips.
More in C#
All C# guidesThe guides filed next to this one in C#, in library order.