Debugging Optimized Code in .NET

Sometime back I found myself trying to remotely debug a program thru visual studio, and while trying to access the value of one of the variables I got a message saying "Cannot evaluate expression because the code of the current method is optimized"... turns out that there are compilation flags that instruct the JIT to optimize the code (usually on release builds) and thus some variables will not be available during debugging.  You may instruct the JIT not to optimize the code by doing the following:

Let's say that you have:

  • DLLYouWantToDebug.dll
  • DLLYouWantToDebug.pdb

 Then you will create a new text file with the same name as the dll you are trying to debug but with "ini" extension, example:

  • DLLYouWantToDebug.ini

Open this file with Notepad and insert the following text in it:

[.NET Framework Debugging Control]


This will override the optimization flag and then you will be able to see all the variable values



Please note that this is not intended for production usage!




The following PowerShell will disable the optimization for the files in a folder or a specific dll/exe.

 Function Set-OptimizationConfigurationFiles
 param (
 [parameter(Mandatory = $true)][ValidateScript ({Test-Path $_})][string] $PathToDeploymentFolder,
 [parameter(Mandatory = $false)][string] $SpecificDll)
 $allDllFiles = Get-ChildItem -Path $pathToDeploymentFolder | Where-Object {($_.Name -like '*.dll' -or $_.Name -like '*.exe') -and ($SpecificDll -eq $null -or $_.Name -eq $SpecificDll)}
 foreach($currentDllFile in $allDllFiles)
 $fileName = $currentDllFile.BaseName
 $iniFullFileName = $currentDllFile.DirectoryName + '\' + $fileName + '.ini'
 '[.NET Framework Debugging Control]' > $inifullFileName
 'GenerateTrackingInfo=1' >> $inifullFileName
 'AllowOptimize=0' >> $inifullFileName