TTT
TTT

Reputation: 28869

C# conditional compilation if assembly exists

I have a project with a reference that may or may not exist. I have code that uses that reference and I'd like to compile it only if the assembly exists. I'm thinking something along the lines of:

#if ASSEMBLY_EXISTS
    AssemblyClass.DoSomething();
#endif

I could put a #define at the top and comment/uncomment as needed, but I'd prefer if it could just somehow know if it's there without my manual intervention, which leads me to believe that #if won't work for this situation. Is there another way to conditionally compile based on whether an assembly exists?

Upvotes: 2

Views: 3264

Answers (2)

Steve Cooper
Steve Cooper

Reputation: 21470

Maybe do it with a condition inside MSBUILD;

It would look something like it

<PropertyGroup>
     <DefineConstants Condition="Exists('my.dll') ">$(DefineConstants);DLLEXISTS</DefineConstants>
</PropertyGroup>

and should go quite far down in your .csproj file.

This reads, roughly, as "redefine the constants by appending DLLEXISTS, if my.dll exists"

Now you should be able to do

#if DLLEXISTS
    // your stuff here
#endif

You might need to fiddle around with the EXISTS expression to find an appropriate relative path.

Upvotes: 7

CathalMF
CathalMF

Reputation: 10055

No you cannot do this. You cannot define the result of a conditional compilation symbol at compile time.

If you want to get fancy you could write a new program which detects the missing assembly and modifies your source. You can then execute this program in the Pre-build event of your project.

The modification of the source could simply be the addition or removal of your suggested #define at the top of the source files.

Upvotes: 1

Related Questions