Compiler Warning (level 3) CS0219

The variable 'variable' is assigned but its value is never used

The compiler issues a level-three warning, when you declare and assign a variable, but do not use it.

Note

The compiler generates this warning only when the variable value is a compile-time constant. Assigning a non-constant expression or method result to a local variable makes it easier to observe those expressions in the debugger. It also makes the result reachable, preventing garbage collection while that variable is reachable.

The following sample shows the cases when and when not the warning is generated:

// CS0219.cs
// compile with: /W:3
public class MyClass
{
   public static void Main()
   {
      var interpolated = "Interpolated";
      var a = 0; // CS0219
      int b = GetZero(); // Doesn't generate a warning.
      var c = "Regular string"; // CS0219
      var d = $"Constant interpolated string"; // Doesn't generate a warning.
      var e = $"{interpolated} string"; // Doesn't generate a warning.
   }

   private static int GetZero()
   {
       return 0;
   }
}