'Is it correct to use Debugger.IsAttached to determinate the environment?

I have only two environments: development and production. Would it be a good idea to use the next code to know if the application is running in one or another?

bool IsProduction()
{
   return !Debugger.IsAttached;
}

I read this and this but it seems to me discussions took a different way.

What about using an appSettings key?

<appSettings>
    <add key="Environment" value="Dev"/>
</appSettings>

What will happen if someone edit the config file? Should the code have a "double-check" mechanism? Should the value be encrypted or is it too much?

Thanks for your time!



Solution 1:[1]

Debugger.IsAttached will only return true if the process has a debugger attached independently of the build (runs under VS or has an external debugger attached).

If you want to diferentiate the environment based on the build type you can use the preprocessor directives to set a boolean, something like this:

#if DEBUG
bool isDebug = true;
#else
bool isDebug = false;
#endif

Solution 2:[2]

The first method using Debugger.IsAttached is not going to work even in development unless you actually have the debugger attached to the process.

Configuration values is a proper approach and probably the best that I know of from a flexibility stand point. You can configure different environments and by using the transformation config files this will be updated during deployment automatically.

If you want more information about the config transformation method I can provide you some links

Solution 3:[3]

You should never assume that Debugger.IsAttached will not run in Production mode. You would get into trouble as you can see that it will unlock developer mode functionalities in PROD mode, if you used code like the following:

if (Debugger.IsAttached())
{
    // Unlock Developer functionalities;
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Gusman
Solution 2 zaid safadi
Solution 3 Sujoy