Search code examples
c#visual-studio-2013csprojcompiler-directives

How to conditionally reference a DLL based on a compilation symbol?


Visual Studio 2013.

I have an external DLL which I am referencing like this in the csproj file:

  <ItemGroup>
    <Reference Include="NameOfDll">
      <HintPath>Path\To\Dll\NameOfDll.dll</HintPath>
    </Reference>

I want this reference to function when a compiler symbol exists and to not function when that compiler symbol does not exist. (To address the first comment, below, let's say the compiler symbol is called Fred.)

This question [ Conditional Reference ] made me think I could add an attribute called Condition to the Reference element shown above but I can't work out what value to give that attribute to effect what I want.

I'd be most happy to be given a way to do this in the VS UI but I'll take any method.


Solution

  • The conditional compilation symbols are in the DefineConstants MSBuild property. Check that this contains your symbol:

    <Reference Include="NameOfDll" Condition="$(DefineConstants.Contains('Fred'))">
      <HintPath>Path\To\Dll\NameOfDll.dll</HintPath>
    </Reference>
    

    Pick a distinctive name for the symbol. Not something that could be a substring of another constant like Debug or Trace.