Exclude code portions with the Conditional attribute

Exclude code portions with the Conditional attribute

VB developers have always used the #IF compiler directive to include or esclude portions of code from the application. The problem with this directive is that you can easily exclude a procedure with a single directive, but it isn’t easy to discard all the calls to that procedure (which would raise a compilation error if you discard the target procedure).

VB.NET gives you a great alternative by means of the Conditional attribute. If you mark a procedure with this attribute the procedure itself will NOT be discarded, but all the calls to it will:

 Sub LogMsg(ByVal MsgText As String)    Console.WriteLine(MsgText)End SubSub TestConditionalAttribute()    LogMsg("Program is starting")    ' ..    LogMsg("Program is ending")End Sub

You can define compilation constants – LOG in the above case – in the Build page of the Project Properties dialog box. You can also use the already-defined TRACE and DEBUG compilation constants. Because the compiler can drop all the calls to the target method- LogMsg, in precedingvious example – the Conditional attribute can only work only with procedures that don’t return a value. If your programming logic requires that a value be returned to the caller, you can use ByRef arguments.

See also  11 Effective Keyword Research Tools and Techniques

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist