views:

452

answers:

3

I have an ASP.NET web application and I have some code that I want to execute only in the debug version. How to do this?

+13  A: 
#if DEBUG
your code
#endif

You could also add ConditionalAttribute to method that is to be executed only when you build it in debug mode:

[Conditional("DEBUG")]
void SomeMethod()
{
}
empi
how does it knows that it's in debug, is it taking it from web.config ?
Omu
@Omu: I added the link to MSDN - it explains there how the compiler selectively removes calls to methods marked `Conditional`.
280Z28
You choose the build mode between release or debug. #if and Conditional are used at compile time. Some more details: http://bytes.com/topic/c-sharp/answers/237540-conditional-debug-if-debug. You will find a lot information about in google.
empi
@Omu: the `DEBUG` in `#if DEBUG` and `Conditional("DEBUG")` is defined as a command-line switch to the C# compiler.
dtb
+1  A: 

I declared a property in my base page, or you can declare it in any static class you have in applicaition:

    public static bool IsDebug
    {
        get
        {
            bool debug = false;
#if DEBUG
            debug = true;
#endif
            return debug;
        }
    }

Then to achieve your desire do:

    if (IsDebug)
    {
        //Your code
    }
    else 
    {
        //not debug mode
    }
Shimmy
I guess you meant #if DEBUG debug = true;#endif
empi
debug will be initialized to false by default, so you IsDebug method will always return false, are u missing the bool debug = true?
Benny
Local variables are **not** initialized to anything, so the current revision doesn't compile in release mode.
dtb
You are right, i changed my code.
Shimmy
+6  A: 

Detecting ASP.NET Debug mode

if (HttpContext.Current.IsDebuggingEnabled)
{
    // this is executed only in the debug version
}

From MSDN:

HttpContext.IsDebuggingEnabled Property

Gets a value indicating whether the current HTTP request is in debug mode.

dtb