How can I disable compiler optimization in C#?
5 Answers
At the command line (csc), /optimize-
In the IDE, project properties → build → "optimize code"
For some JIT optimizations, you can use [MethodImpl(...)]

- 39,551
- 56
- 175
- 291

- 1,026,079
- 266
- 2,566
- 2,900
-
If you don't specify /optimize you get the same behaviour as /optimize- – Brian Lyttle Jul 29 '09 at 10:21
-
12specifically use [MethodImpl(MethodImplOptions.NoOptimization)] on methods that you want to skip optimization for. Use case: in certain scenarios, where a native call calls another native call, the compiler will generate invalid IL code, and the runtime will throw a InvalidProgramException when you try to run it. You can either turn off optimization for the whole program, or selectively use [MethodImpl(MethodImplOptions.NoOptimization)] on the methods that are using the native calls. I had to do exactly this to resolve that problem in a recent application I was working on... – Troy Howard Aug 21 '09 at 02:12
-
2[MethodImpl(MethodImplOptions.NoOptimization)] isn't working at all. I've put it on every single method in the call stack and it has no effect. – vbullinger Feb 21 '13 at 23:04
-
1@vbullinger step back a bit... what is it that you are trying to disable? what are you looking at to decide whether it is optimized or not? note that this is a flag to the JIT compiler, not to the C# compiler. – Marc Gravell Feb 22 '13 at 00:16
-
A calls B which calls C which calls D which calls E. In E, I want to jump up the stack frame to C. It's jumping to A. C and D have disappeared. This is bad as I'm looking for the method name of C. Works in debug mode. – vbullinger Feb 22 '13 at 14:54
-
3In that case, you want to add [MethodImpl(MethodImplOptions.NoInlining)] to C and D. This informs the complier that these methods cannot be inlined into the caller's implementation – Eric W Jun 02 '17 at 13:43
-
Found this comment chain on a search for a totally unrelated problem. This probably would have worked, Eric :) – vbullinger Nov 10 '17 at 19:28
You can disable the optimizations in runtime using an .ini file: http://msdn.microsoft.com/en-us/library/9dd8z24x.aspx
Enter the following text into you .ini [for example Explorer.ini]
[.NET Framework Debugging Control]
GenerateTrackingInfo=1
AllowOptimize=0

- 21,122
- 31
- 128
- 207
In Visual Studio I believe you can just create a debug build, but it includes additional debug information. Project Properties (right click on project in solution) gives you access to the controls governing compilation.
If you build on the command line with csc.exe see the /optimize parameter docs. If you don't specify /optimize then the assembly should not be optimized.

- 14,558
- 15
- 68
- 104
before you start to change the settings of the project which might find its way to production verify that your solution configuration is set for Debug and not Release.
I had the same issue and then I saw that it was set to Release by mistake...

- 1,633
- 1
- 20
- 32