What does "Cannot evaluate expression because the code of the current method is optimized." mean?
Solution 1:
While the Debug.Break() line is on top of the callstack you can't eval expressions. That's because that line is optimized. Press F10 to move to the next line - a valid line of code - and the watch will work.
Solution 2:
The Debugger uses FuncEval to allow you to "look at" variables. FuncEval requires threads to be stopped in managed code at a GarbageCollector safe point. Manually "pausing" the run in the IDE causes all threads to stop as soon as possible. Your highly recursive code will tend to stop at an unsafe point. Hence, the debugger is unable to evaluate expressions.
Pressing F10 will move to the next Funceval Safe point and will enable function evaluation.
For further information review the rules of FuncEval.
Solution 3:
You are probably trying to debug your app in release mode instead of debug mode, or you have optimizations turned on in your compile settings.
When the code is compiled with optimizations, certain variables are thrown away once they are no longer used in the function, which is why you are getting that message. In debug mode with optimizations disabled, you shouldn't get that error.
Solution 4:
This drove me crazy. I tried attaching with Managed and Native code - no go.
This worked for me and I was finally able to evaluate all expressions :
- Go into Project / Properties
- Select the Build tab and click Advanced...
- Make sure Debug Info is set to "full" (not pdb-only)
- Debug your project - voila!