Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent C# compiler/CLR from optimizing away unused variables in DEBUG builds?

Tags:

c#

debugging

While debugging I tried to save intermediate results of a calculation to a variable so that when a breakpoint condition is met I could check that value. However C# compiler (or CLR) optimized away that variable as unused. I solved the problem by making the variable a public field of the class, however I'd like to know if there is a straightforward solution to this problem.

"Optimize code" checkbox is unchecked. The build configuration is Debug.

Edit: Found that it only affects some unused variables in iterators that would normally end up as fields in the automatically generated iterator class; unused variables that are scoped within blocks not containing yield statements are retained.

like image 862
srgstm Avatar asked Feb 03 '23 12:02

srgstm


1 Answers

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.

like image 135
Marc Gravell Avatar answered Feb 06 '23 12:02

Marc Gravell