Wednesday, March 13, 2013

Conditionally referencing DEBUG and RELEASE builds in Visual Studio projects

This is a little neat trick I learned from someone on stackexchange.com.  When adding a reference to an assembly in Visual Studio projects one can choose only one type of the assembly build DEBUG or RELEASE. There is no way in the IDE to reference DEBUG assembly when making DEBUG builds of your projects and reference RELEASE assembly when making RELEASE builds.  But this can be achieved by directly editing the project file (extension .csproj for a C# project, for example) in any text editor. A typical hint path entry for the referenced assembly looks like this

    <Reference Include="ReferenceAssembly, Version=1.0.0.0, Culture=neutral, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\..\externals\Release\ReferenceAssembly.dll</HintPath>
</Reference>



The project file is in MSBUILD format and that allows us to use built-in project property $(Configuration) to conditionally point to different locations of the same assembly depending on the current build configuration of DEBUG or RELEASE

    <Reference Include="ReferenceAssembly, Version=1.0.0.0, Culture=neutral, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\..\externals\$(Configuration)\ReferenceAssembly.dll</HintPath>
</Reference>



In this case, when making a DEBUG build of project the ReferenceAssembly.dll from ..\..\..\externals\Debug\ folder will be referenced. And when making RELEASE build the assembly will be picked up from ..\..\..\externals\Release\ folder.




In fact, we can also choose to reference assemblies in different paths like this

<Reference Include="ReferenceAssembly, Version=1.0.0.0, Culture=neutral, processorArchitecture=MSIL">   
<HintPath Condition="'$(Configuration)' == 'Debug'">..\..\..\path1\ReferenceAssembly.dll</HintPath>
<HintPath Condition="'$(Configuration)' == 'Release'">..\..\..\path2\ReferenceAssembly.dll</HintPath>
</Reference>