vladeck's junkyard

designer wannabe

Conditional referencing in .NET

on November 17, 2010

If you ever happen to stumble upon a problem of having the need to support multiple versions of the same assembly in your .NET project, read on… Take these two assemblies for example:

Foo.dll (v1.0)

namespace Foo
{
    class Bar
    {
        public void Do()
        {
            Console.WriteLine("Hello, from v1.0 of Bar");
        }
    }
}

Foo.dll (v2.0)

namespace Foo
{
    class Bar
    {
        public void Do(string parameter)
        {
            Console.WriteLine("Hello, from v2.0 of Bar with parameter: {0}", parameter);
        }
    }
}

So, now we have two Foo.dll assemblies that are of different version and we want to use them in our project. First, copy these assemblies to project directory and put them under v1 and v2 directories (at the same level as the .csproj file); then, open the .csproj file and add the following configurations (I’ll do this for DEBUG versions – just copy DEBUG that is already there and modify it; the RELEASE is similar):

<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug - v1|AnyCPU' ">
    <DebugSymbols>true</DebugSymbols>
    <OutputPath>bin\Debug\v1\</OutputPath>
    <DefineConstants>TRACE;DEBUG;V_ONE</DefineConstants>
    <DebugType>full</DebugType>
    <PlatformTarget>AnyCPU</PlatformTarget>
    <ErrorReport>prompt</ErrorReport>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug - v2|AnyCPU' ">
    <DebugSymbols>true</DebugSymbols>
    <OutputPath>bin\Debug\v2\</OutputPath>
    <DefineConstants>TRACE;DEBUG;V_TWO</DefineConstants>
    <DebugType>full</DebugType>
    <PlatformTarget>AnyCPU</PlatformTarget>
    <ErrorReport>prompt</ErrorReport>
</PropertyGroup>

And here comes the good part, just below previous modification:

<Choose>
    <When Condition=" '$(Configuration)' == 'Debug - v1'">
      <ItemGroup>
        <Reference Include="Foo">
          <SpecificVersion>False</SpecificVersion>
          <HintPath>v1\Foo.dll</HintPath>
        </Reference>
      </ItemGroup>
    </When>
    <When Condition=" '$(Configuration)' == 'Debug - v2'">
      <ItemGroup>
        <Reference Include="Foo">
          <SpecificVersion>False</SpecificVersion>
          <HintPath>v2\Foo.dll</HintPath>
        </Reference>
      </ItemGroup>
    </When>
</Choose>

Now you are ready to choose your build configuration, and have code support multiple version of the same assembly:

var b = new Foo.Bar();

#if (V_ONE)
   b.Do();
#elif (V_TWO)
   b.Do("Hello");
#endif

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.