How to Resolve Warning "CS0164: This label has not been referenced" in C#
The Compiler Warning CS0164 is a code cleanup warning. The message reads: "This label has not been referenced".
In C#, you can define a Label (an identifier followed by a colon, e.g., Start:) to mark a specific spot in your code for use with goto statements. This warning occurs when you define a label but never actually write a goto statement that targets it. While this doesn't break your application, unreferenced labels add clutter and can make code harder to read.
This guide explains why this warning appears and how to clean up your code.
Understanding Labels and Goto
A label creates a jump destination.
- Definition:
MyLabel: - Usage:
goto MyLabel;
If you define the destination (MyLabel:) but the compiler scans your method and finds zero instructions to jump there (goto MyLabel;), the destination serves no purpose. It is "dead code" infrastructure.
Scenario 1: Leftover Debugging or Refactoring
This is the most common cause. You might have used goto temporarily to skip a section of code during debugging, or you refactored a method and removed the goto logic but forgot to delete the label itself.
Example of error
public void ProcessData()
{
Console.WriteLine("Step 1");
// ⛔️ Warning CS0164: This label has not been referenced.
// Nothing in this method says 'goto SkipStep;'
SkipStep:
Console.WriteLine("Step 2");
}
Solution: Remove the Label
Simply delete the label identifier and the colon.
public void ProcessData()
{
Console.WriteLine("Step 1");
// ✅ Correct: Label removed. Logic flows naturally.
Console.WriteLine("Step 2");
}
Scenario 2: Commented Out Jumps
Sometimes developers comment out the goto statement while testing, leaving the label active. The compiler sees the label as "orphaned."
Example of error
public void Validate(bool isValid)
{
if (!isValid)
{
// goto Error; // <--- Logic commented out
}
Console.WriteLine("Success");
return;
// ⛔️ Warning CS0164: No active code references this.
Error:
Console.WriteLine("Failed");
}
Solution: Clean Up or Restore
- If the logic is needed: Uncomment the
goto. - If the logic is obsolete: Remove the
Error:label (and ideally the dead code following it, which might trigger CS0162 Unreachable code).
public void Validate(bool isValid)
{
if (!isValid)
{
// Alternative: Use a method call or throw instead of goto
Console.WriteLine("Failed");
return;
}
Console.WriteLine("Success");
}
Conclusion
CS0164 is a reminder to keep your code tidy.
- Identify the Label: Look for
Name:identifiers. - Search for Usage:
Ctrl+Ffor the label name inside that method. - Delete: If you find no usage, delete the label definition.