0

How can I build .NET assembly in debug mode without optimization?

dotnet build --configuration Debug

I built a simple .Net Core console app with the above command, but the compiler still optimized my code, what can I do to prevent it?

This is my original Factorial function:

public int Factorial(int num)
{
    int num_aux;
    if (num < 1) num_aux = 1;
    else num_aux = num * (this.Factorial(num - 1));
    return num_aux;
}

And .NET Reflector outputs the decompiled function. As you see the compiler removes the local variable num_aux:

public int Factorial(int num)
{
    if (num < 1)
    {
        return 1;
    }
    return (num * this.Factorial(num - 1));
}

IL output:

.method public hidebysig instance int32 ComputeFac(int32 num) cil managed
{
    .maxstack 4
    .locals init (
        [0] int32 num2,
        [1] bool flag,
        [2] int32 num3)
    L_0000: nop 
    L_0001: ldarg.1 
    L_0002: ldc.i4.1 
    L_0003: clt 
    L_0005: stloc.1 
    L_0006: ldloc.1 
    L_0007: brfalse.s L_000d
    L_0009: ldc.i4.1 
    L_000a: stloc.0 
    L_000b: br.s L_0019
    L_000d: ldarg.1 
    L_000e: ldarg.0 
    L_000f: ldarg.1 
    L_0010: ldc.i4.1 
    L_0011: sub 
    L_0012: call instance int32 Fac::ComputeFac(int32)
    L_0017: mul 
    L_0018: stloc.0 
    L_0019: ldloc.0 
    L_001a: stloc.2 
    L_001b: br.s L_001d
    L_001d: ldloc.2 
    L_001e: ret 
}
MiP
  • 5,846
  • 3
  • 26
  • 41
  • 1
    [Asked and answered](https://stackoverflow.com/questions/1199204/how-can-i-disable-compiler-optimization-in-c) ... – txtechhelp Jan 04 '18 at 04:50
  • @txtechhelp The checkbox is unchecked for Debug mode by default. – MiP Jan 04 '18 at 04:55
  • Your question indicates you're using the command line, which the answer says to use the switch `/optimize-` .. have you done that? – txtechhelp Jan 04 '18 at 04:57
  • @txtechhelp I don't know how to use csc flags for [dotnet cli tools](https://learn.microsoft.com/en-us/dotnet/core/tools/dotnet-build?tabs=netcore2x). Could you help me how to apply flags for .net apps in Linux/MacOS machines? – MiP Jan 04 '18 at 05:04
  • Be aware that the output you get from reflector or any other decompiler is just an equivalent of the real bytecode in c#. Did you check if the local variable is still there on il level? – thehennyy Jan 04 '18 at 07:13

0 Answers0