Site icon Learn by Insight…

“Cannot evaluate expression because the code of the current method is optimized”

This is one the common error faced by a lot of Visual Studio users.

Problem description

Typically, they get the below error message during debugging:

“Cannot evaluate expression because the code of the current method is optimized.”

Assessment

In .NET, “Function Evaluation (funceval)” is the ability of CLR to inject some arbitrary call while the debuggee is stopped somewhere. Funceval takes charge of the debugger’s chosen thread to execute requested method. Once funceval finishes, it fires a debug event. Technically, CLR have defined ways for debugger to issue a funceval.

CLR allows to initiate funceval only on those threads that are at GC safe point (i.e. when the  thread will not block GC) and Funceval Safe (FESafe) point (i.e. where CLR can actually do the hijack for the funceval.) together.

Thus, possible scenarios for CLR, a thread must be:
1. stopped in managed code  (and at a GC safe point): This implies that we cannot do a funceval in native code. Since, native code is outside the CLR’s control, it is unable to setup the funceval.
2. stopped at a 1st chance or unhandled managed exception (and at a GC safe point): i.e at time of exception, to inspect as much as possible to determine why that exception occurred. (e.g: debugger may try to evaluate and see the Message property on raised exception.)

Overall, common ways to stop in managed code include stopping at a breakpoint, step, Debugger.Break call, intercepting an exception, or at a thread start. This helps in evaluating the method and expressions.
Refer: MSDN Blog: Rules of Funceval

Possible resolutions

Based on the assessment, if thread is not at a FESafe and GCSafe points, CLR will not be able to hijack the thread to initiate funceval. Generally, following helps to make sure funceval initiates when expected:

Step #1:
Make sure that you are not trying to debug a “Release” build. Release is fully optimized and thus will lead to the error in discussion. By using the Standard toolbar or the Configuration Manager, you can switch between Debug & Release.
For more details about it: How to: Set Debug and Release Configurations

Step #2:
If you still get the error, “Debug option” might be set for optimization. Verify & Uncheck the “Optimize code” property under Project “Properties”:

Step #3:
If you still get the error, “Debug Info” mode might be incorrect. Verify & set it to “full” under “Advanced Build Settings”:

Step #4:
If you still face the issue, try the following:

Conclusion

It’s not an error but an information based on certain settings and as designed based on how .NET runtime works.

Keep learning!