How to prevent C# compiler/CLR from optimizing away unused variables in DEBUG builds?
The lazy option would be.... use the value, ideally in a way that doesn't allow it to be held on the stack. For example:
var tmp = SomeMethod();
// your other code
Debug.WriteLine(tmp);
the use of the value as an argument means it must be retained, but that line is automatically not compiled into release builds.
However! I must emphasize that locals are pretty-much always retained in an unoptimized/debug build, so I'm finding the scenario from the question hard to envisage.
If you are using Visual Studio, why not just add a breakpoint on the line following the line on which the calculation is being made, and then you can simply hover over the calculation to see the result in the intellisense/tooltip popup? I also think that you can add the calculation to the "watch" screen and view the result that way as well.
This is usually how I view the results of things I am debugging. Alternatively, you could just use the temp variable you created in some simple way to avoid getting the warning.
For example:
Console.Write(tempVariable);
Handy utility:
using static _globals;
static class _globals
{
[MethodImpl(MethodImplOptions.NoInlining), DebuggerHidden]
public static void Nop<T>(out T x) => x = default(T);
};
class Program
{
static void Main()
{
int i; // unreferenced variable
/// ...
Nop(out i);
/// ...
}
};