Be careful! System.Diagnostics.Debugger.IsAttached and #if DEBUG (or
the equivalent [Conditional("DEBUG")] ) have different effects! It
depends upon what you want!
#if DEBUG
and
[Conditional("DEBUG")]
tell the compiler to include the code (or the method) only for a _Debug
build_. So, if you compile the code under the Debug configuration (see
Configuration Manager under the Build menu), then the code will be
included. If you compile the code under the Release configuration then
the code will not be included.
It does not matter whether you run the Debug configuration under
debugger control, or run it from the command line. Code included using
#if DEBUG will exist and execute no matter how the application is run.
Similarly, the Release assembly will not include the code, so no matter
how it is run the code will never execute (because it's not compiled
in).
System.Diagnostics.Debugger.IsAttached produces a different effect: the
code is always compiled in, in all configurations. However, it runs
_only if_ the application is running under control of the debugger.
Even if you compile the Debug configuration, if you run it from the
command line (with no debugger), code within an
if (System.Diagnostics.Debugger.IsAttached)
{
... code here ...
}
will not execute, because the executable is not running under debugger
control.