[c#] "Cannot evaluate expression because the code of the current method is optimized" in Visual Studio 2010

I am using Visual Studio 2010 in debug mode and I have "optimize code" unchecked. I can't quick watch (or hover on) any variable in the debugger. I get this error "Cannot evaluate expression because the code of the current method is optimized".

Even a line like: int i = -3, doing a quick watch on i, I get "Cannot obtain value of local or argument 'i' as it is not available at this instruction pointer, possibly because it has been optimized away."

This link referenced in a similar question doesn't seem to apply.

Is there a setting I am missing?

This question is related to c# visual-studio visual-studio-2010

The answer is


If you're trying to debug an ASP.NET project, ensure that the project's Properties > Web > Servers dropdown is set to "IIS Express" (in addition to checking everything else here).


I had this issue when I was using VS 2010. My solution configuration has (Debug) selected. I resolved this by unchecking the Optimize Code property under project properties. Project (right Click)=> Properties => Build (tab) => uncheck Optimize code


When you see the "Cannot evaluate expression because the code of the current method is optimized." message after issuing a Debugger.Break() statement then please make sure you press F10 to step to the next statement.

Once stepped to the next statement, and assuming you are running a Debug build, this message should disappear.


My situation was not covered by any of the above answers. I found the following: MSDN article on threading that explains that when stuck in some primitive native threading operations, the debugger can't access the data. As an example, when a thread is sitting on Task.Wait(), this comes up.


Apart from @Kragen mentioned, If you are debugging a web project

close the visual studio and try deleting the temporary files at C:\Windows\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files


I had the same issue in VS 2010. Cleaned-up and rebuild the solution and it worked.


I had the same problem while debugging a class library from a testbed web app. I was referencing the release version in the testbed and that was set to be optimised in the class library properties.

Un-ticking the optimise code checkbox for the release version in the class library properties, just while I am writing it, has solved the issue.


I had mixed c++/cli mfc extension dlls, that were optimised even if debug configuration (seen from VS 2017 Modules window). As previous answer suggested I changed "In VS2013 go to: Tools -> Options -> Debugging -> General and enable 'Use managed compatibility mode'. This disables the new function evaluation behavior." That settings find also in VS 2017.

But that was not enough, so I also copied the UseDebugLibraries setting from another MFC app's project file to extension dll project file.

    <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
      ...
      <UseDebugLibraries>true</UseDebugLibraries>

Then rebuild and that fixed the problem.


Try to run in debug mode.If you are running in release mode you will get this message.


I started receiving this message when I migrated to Visual Studio 2017. None of the ideas on this page that I tried worked for me. On another post I found this suggestion and it DID work - remove:

[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]

...from your AssemblyInfo file.


vickramds's comment above, referring to http://torulflundgren.blogspot.com.au/2010/03/cannot-obtain-value-of-local-or.html , did it for me. I checked everything - deleted all the dll, pdb files from local bin folders, Clean, Rebuild, cleared all folders of Temporary ASP.NET Files, ensured TRACE/DEBUG flags were set, checked the DLL paths, etc.

To put it down so it isn't lost, for the affected project(s):

Project Properties --> Build --> Advanced --> Debug Info: Full.

You want to check that you have the Debug configuration selected before you do this, unless of course, you intended otherwise.


I had this problem with an F# project that had been here and there between Visual Studio and MonoDevelop, perhaps originating in the latter (I forget). In VS, the optimize box was unchecked, yet optimization certainly seemed to be occuring as far as the debugger was concerned.

After comparing the XML of the project file against that of a healthy one, the problem was obvious: the healthy project had an explicit <optimize>false</optimize> line, whereas the bad one was missing it completely. VS was obviously inferring from its absence that optimization was disabled, while the compiler was doing the opposite.

The solution was to add this property to the project file, and reload.


I had the same problem. But in my case, the Debuggable attribute was hard coded in the AssemblyInfo.cs file of my project and therefor not (over-)written by compilation. It worked after removing the line specifying the Debuggable attribute.


It sounds like you are debugging an optimised / release build, despite having the optimised box un-checked. Things you can try are:

  • Do a complete rebuild of your solution file (right click on the solution and select Rebuild all)
  • While debugging open up the modules window (Debug -> Windows -> Modules) and find your assembly in the list of loaded modules. Check that the Path listed against your loaded assembly is what you expect it to be, and that the modified timestamp of the file indicates that the assembly was actually rebuilt.
  • The modules window should also tell you whether or not the loaded module is optimised or not - make sure that the modules window indicates that it is not optimised.

If you cant't see the Modules menu item in the Debug -> Windows menu then you may need to add it in the "Customise..." menu.


Regarding the problem with "Optimize code" property being UNCHECKED yet the code still compiling as optimized: What finally helped me after trying everything was checking the "Enable unmanaged code debugging" checkbox on the same settings page (Project properties - Debug). It doesn't directly relate to the code optimization, but with this enabled, VS no longer optimizes my library and I can debug.


I had the same problem in VS2008. In my case it was solved via solution-rebuild.


For me it was happening in VS2017 and VS2019. It stopped happening after I selected the option "Suppressed JIT optimization on module load".

enter image description here


One other thing that you may do is, create a file with the same name as the dll that is optimized but with ini extension and add the following to it:

[.NET Framework Debugging Control]
GenerateTrackingInfo=1
AllowOptimize=0

This will tell the JIT not to optimize your variables.

Note that you still need the pdb, so you will end up with something like this: yourDll.dll yourDll.pdb yourDll.ini

This works specially well in scenarios when you don't have access to re-generate the dlls with debug option.

http://www.hanselman.com/blog/DebugVsReleaseTheBestOfBothWorlds.aspx


In VS2013 go to: Tools -> Options -> Debugging -> General and enable 'Use managed compatibility mode'. This disables the new function evaluation behavior.


In Visual Studio 2012 enabling the "Managed" option from Tools > Debugging > Just-In-Time worked for me.

enter image description here


I realize this is a later answer, but I found another reference to a way to address this issue that might help others in the future. This web page describes setting an environment variable (COMPLUS_ZapDisable=1) that prevents optimization, at least it did for me! (Don't forget the second part of disabling the Visual Studio hosting process.) In my case, this might have been even more relevant because I was debugging an external DLL thru a symbol server, but I'm not sure.


Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to visual-studio

VS 2017 Git Local Commit DB.lock error on every commit How to remove an unpushed outgoing commit in Visual Studio? How to download Visual Studio Community Edition 2015 (not 2017) Cannot open include file: 'stdio.h' - Visual Studio Community 2017 - C++ Error How to fix the error "Windows SDK version 8.1" was not found? Visual Studio Code pylint: Unable to import 'protorpc' Open the terminal in visual studio? Is Visual Studio Community a 30 day trial? How can I run NUnit tests in Visual Studio 2017? Visual Studio 2017: Display method references

Examples related to visual-studio-2010

variable is not declared it may be inaccessible due to its protection level SSIS Excel Connection Manager failed to Connect to the Source This project references NuGet package(s) that are missing on this computer Gridview get Checkbox.Checked value error LNK2038: mismatch detected for '_MSC_VER': value '1600' doesn't match value '1700' in CppFile1.obj What is the difference between Visual Studio Express 2013 for Windows and Visual Studio Express 2013 for Windows Desktop? Attach (open) mdf file database with SQL Server Management Studio What is and how to fix System.TypeInitializationException error? Could not load file or assembly "Oracle.DataAccess" or one of its dependencies IIS error, Unable to start debugging on the webserver