How to use #IF DEBUG in VB.NET

Viewed 55072

Is it possible to assign a value to a class variable from inside a #IF DEBUG conditional?

I want to conditionally execute some code from inside my main form load if I am running in DEBUG mode. I thought I could do something like:

Public Class Form1
    public DEB as Integer

    #if DEBUG then
        DEB = 1
    #else
        DEB = 0
    #end if

    Private Sub Form1_Load(....)
        if DEB=1 Then
            <do something>
        else
            <do something else>
        end if
    ....

However, it seems like you can't assign a value to a variable. I'm obviously not understanding the scoping correctly. I can't seem to put the #if DEBUG inside the Load sub routine. How do I do this?

3 Answers

I don't see your problem here. I do this and it works fine. It's a bit annoying that the compilation constant isn't available directly to running code but it makes sense when you think about it.

In response to Christian, I think the case against just enclosing your code in the compiler directives is that with a code variable you can write cleaner, more descriptive code with potentially less duplication and therefore simpler maintenance.

For example, here's my standard library code:

Public Module Common

    #if DEBUG then
        Public In_Debug As Boolean = True
    #else
        Public In_Debug As Boolean = False
    #end if
End Module

Public Class Form1

    Private Sub Form1_Load(....)

        If In_Debug Then SplashScreen.Hide()
        ...

Placing the In-Debug code variable in a public module effectively makes it a Global which you can treat as a constant throughout your project.

(Example explanation: I don't show the splash screen in debug because it may hide dialogs, etc which can stop you progressing.)

Obviously, you can do the same thing with the TRACE constant or any custom compiler constant you choose to declare.

And, yes, as GregH mentioned, you need to make sure that you actually have a DEBUG constant declared in your project's Debug configuration (whether or not it's actually called "Debug"). You don't need it declared in Release; it's absence is interpreted as "False".

In VB.NETFramework v4.5

Debugger.IsAttached

Public DEB As Integer
If Debugger.IsAttached Then
    DEB = 1
Else
    DEB = 0
End If
Related