OdeToCode IC Logo

Conditional Compilation In ASP.NET 2.0

Friday, December 2, 2005

Conditional compilation allows you to select sections of code to include or exclude from compilation depending on the presence of a constant. This feature is available in both C# and VB.NET. The following page needs DEBUG and MYCONSTANT defined to execute both Response.Write methods at runtime.

protected void Page_Load(object sender, EventArgs e)
    #if DEBUG
    Response.Write("DEBUG is defined <br/>");

"MYCONSTANT is defined <br />");

In 1.1 it was easy to define constants for a web project, but there is no project property page with this option in 2.0. The ASP.NET platform controls compilation, so we need to feed ASP.NET the information.

First, ASP.NET will define a DEBUG constant when debug=”true” in the <compilation> section of web.config. Unfortunately, the IDE isn't smart enough to detect when DEBUG is defined. If the IDE thinks code is excluded from compilation, it greys out the text.

For your own constants, it gets a little trickier. For example, to define MYCONSTANT there are two options. One option is to define MYCONSTANT for a single page at a time using CompilerOptions in the page directive like so (/d works for csc and vbc compilers):

<%@ Page Language="C#" ... CompilerOptions="/d:MYCONSTANT" %>

Of course, you probably want all code in the web project to see the constant, so you can change the compiler options in web.config.

language="c#;cs;csharp" extension=".cs" 
         type="Microsoft.CSharp.CSharpCodeProvider, System, Version=, Culture=neutral, PublicKeyToken=b77a5c561934e089" />           

Having said all this, the default settings for medium trust do not allow you to fiddle with compiler options (I imagine this is to prevent someone from throwing the /unsafe switch, for example). Keep this in mind if you use conditional compilation and rely on dynamic compilation in a hosted environment.