9

I was wondering if there is a way to conditionally compile entire namespaces in C#. Or am I left with having to explicitly decorate each source file within the namespace with the preprocessor directives to exclude it? In sub-versions of my application the code in various namespace is simply not required and I would like it excluded.

Thanks in advance!

0

4 Answers 4

4

If your namespace is in a separate assembly which doesn't contain anything else you can use the Configuration Manager for your specific sub-version and untick the "Build" check box.

If you've got other classes in the assembly though they will not be built or included obviously, and then the only way would be to decorate with pre-processor declarations.

1

You would need to put the conditional compilation directive in each file. There is no way to mark an entire namespace as conditionally compiled.

As Michael notes in his answer, a possible solution is to break out the conditional code into a separate project (assembly), and ship that assembly only for configurations that require it; but this will depend on the nature of the conditional code.

1
  • Thank you for this additional clarification.
    – Filip K
    Apr 7, 2010 at 3:59
1

You can do this by decorating each file, or you could do it by choosing which files to include. Both MSBuild and csc have options for including all files under a path, and MSBuild additionally has the ability to conditionally include build items based on an attribute (rather than requiring a separate csproj per configuration).

But it is probably easier to decorate the files directly ;-p

1

I had the same problem, and using directives in each file eventually became too much work; so I started using conditional <ItemGroup> tags in the .csproj file.

For example, if I need to exclude some files from a build, I will move these files into a new <ItemGroup> section...

<ItemGroup Condition=" '$(SlimBuild)' != 'true' ">
...
</ItemGroup>

...and call msbuild.exe with a matching property parameter.

MSBuild.exe MyApp.msbuild /p:Configuration=Release /p:SlimBuild=true

You could probably also use wildcards to include future files.

<ItemGroup>
  <Compile Include=".\SomePath\*.cs" />
</ItemGroup>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.