Search code examples
c#.net-corecompiler-options

How do I use "-optimize" with dotnet cli?


Up until now I've been using csc.exe from .NET Framework to compile my short C# scripts. Nothing too fancy, I just wanted to explore a bit and the csc.exe was already on my computer. Now that I'm trying to write my projects using the .NET Core sdk (which I found here: https://dotnet.microsoft.com/download/dotnet-core/3.1), I am not sure how to specify those classic compiler options such as "-optimize".

I am aware that I don't really need "-optimize", but I would still like to experiment and maybe use some other options that I haven't considered yet. The only solution that I came up with was using the provided csc.dll (using "dotnet <path>/csc.dll ...") which meant going full circle back to csc.exe which kind of defeated the purpose of the whole sdk.

How to reproduce this situation:

  • new folder
  • "dotnet new console"
  • all nececery files are now generated ("Project.csproj", "Program.cs", "bin/", "obj/...")
  • "dotnet run"
  • what now?

I assume I need to add something to the .csproj file since it has "<AllowUnsafeBlocks>true</AllowUnsafeBlocks>" for "-unsafe" however, I haven't found anything for "-optimize".

Additional info: Im using Visual Studio Code, which I don't think is relevant for this problem, but just in case.


Solution

  • Compiling for "release" automatically turn that option on. To use that, pass -c Release to the dotnet command.

    For example, Release points to a configuration that looks something like this:

    <PropertyGroup Condition="'$(Configuration)' == 'Release'">
        <DefineConstants>$(DefineConstants);RELEASE;TRACE</DefineConstants>
        <DebugSymbols>false</DebugSymbols>
        <DebugType>portable</DebugType>
        <Optimize>true</Optimize>
    </PropertyGroup>
    

    More information here.