Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

#if DEBUG vs if (env.IsDevelopment())

It seems that Preprocessor Directives (#if DEBUG) and ASP.NET Core Environment Name (IHostingEnvironment.EnvironmentName) both could be used when you want to have different behavior in debug/development and release/production. When is it appropriate to use one over the other is there any reason to prefer one over the other

Example with #if DEBUG

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    #if DEBUG
        app.UseDeveloperExceptionPage();
        app.UseBrowserLink();
    #else
        app.UseExceptionHandler("/Error");
    #endif
}

Example with env.IsDevelopment()

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
        app.UseBrowserLink();
    }
    else
    {
        app.UseExceptionHandler("/Error");
    }
}

Update: This question I am looking for when should use the ASP.NET Core environment name (a new feature of .NET core). This is different then the other question regarding #if and conditional attribute

like image 638
webwake Avatar asked Feb 12 '18 20:02

webwake


1 Answers

Preprocessor directives are conditionally compiled...

Which means that something like this:

#if DEBUG
    //Do something
#endif

Will only be compiled and checked if the DEBUG symbol is defined (it is defined when the build is set to DEBUG). Additionally, in the IDE the code between the preprocessor symbols will appear greyed out.

This code:

if (env.IsDevelopment())
{
    //Do something
}

Is compiled for both release/debug environments. The key here is that the code exists and the tests are run regardless of the environment being debug/release. In more complicated scenarios this has two effects:

  • The execution of the code may be slower
  • The executable will be larger

Additionally including debug code in a release environment may be giving away some trade secrets or other vital information if released. Where possible try to avoid releasing debug code in release mode.

like image 64
Ron Beyer Avatar answered Oct 09 '22 19:10

Ron Beyer