Reputation: 1233
I have a class library A that is used in other projects in my solution like B and C.
Class library A behaves differently based on the presence of a pre-processor directive, for example :
#if some_directive
// some code
#else
// some other code
#end
How can I use class library A in project B with enabled some_directive
but use in project C with disabled some_directive
?
Upvotes: 7
Views: 3025
Reputation: 11
I Know this topic is old - for me the following approach works nicely and might fit as well: comments of (dis)advantages of this approach are welcome. If you add your .cs-file as existing Item as a link to each project - you can compile it with different directives For adding an existing item as a linked file see screenshots at this post Use folders to organize linked files.
// file ClassA.cs
namespace HelperClasses
{
public ClassA
{
#if some_directive
// some code
#else
// some other code
#end
// ....
}
}
// using statement in Project B and C
using HelperClasses
// Add ClassA.cs in both Projects B and C
// as exiting, linked File -- not as a Reference
// set the compiler-Directives according your needs
Upvotes: 0
Reputation: 1233
It seems that currently this feature is not supported. According to this post:
The language doesn't support the notion of references via preprocessor macros. What you can do is use a msbuild file and alter the set of references added based on msbuild parameters.
Another workaround which I used was using solution configuration in "Configuration Manager". I created two configurations for building each projects B or C which preprocessor directive is enabled in only one of these configurations.
Upvotes: 1
Reputation: 109852
You can do something like this using the ConditionalAttribute
This is how Debug.WriteLine()
is present or non-present depending on presence of the "DEBUG" symbol.
You will be able to define your own name for the conditional symbol that you use to control the presence or absence of the code.
You can then put that symbol into the list in the "Conditional compilation symbols" settings on the project properties "Build" tab for the project where you want the code.
This doesn't allow you to have the "some other code" part unfortunately, and also it only applies to entire methods.
Upvotes: 1