How can I test if code is running in debug mode?

  • Thread starter Thread starter Wysiwyg
  • Start date Start date
W

Wysiwyg

Is there any way besides adding a specific debug command line argument for
the project to tell if an application is running in debug mode?

Thanks!
Bill
 
I think you can also use:

public void Foo1()
{
If (Debugger.IsAttached)
Foo2();
}

or

[Conditional("DEBUG")]
public void Foo1()
{
Foo2();
}
 
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.
 
Thanks to both of you!

Bill

John Timney (ASP.NET MVP) said:
You can test against conditional directives to get your code to tell you
what mode its in

private void Test()
{
#if DEBUG
Console.WriteLine("In Debug..");
#endif
}

See here:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/csref/html/vclrfif.asp

--
Regards

John Timney
ASP.NET MVP
Microsoft Regional Director

ESPNSTI said:
I think you can also use:

public void Foo1()
{
If (Debugger.IsAttached)
Foo2();
}

or

[Conditional("DEBUG")]
public void Foo1()
{
Foo2();
}
 
one correction, methods marked with ConditionalAttribute are always included
in the compiled dll. only the calling code is omitted depending on the
symbol defined. otherwise, methods like Debug.XXX and Trace.XXX would've
never made it into the BCL.
 
Search for: Ollydbg.exe An excellent debugger of which version 10 or later
has been posted. From the "readme"..."OllyDbg 1.10 is a 32-bit
assembler-level analyzing debugger for
Microsoft(R) Windows(R) with intuitive interface."
"http://home.t-online.de/home/Ollydbg"
 
Back
Top