Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I conditionally enable attributes in C#? "#if DEBUG" isn't working

The trusty old preprocessor directive in C# appear to work great when I write:

#if DEBUG
...
(Some code)
...
#endif

However, attributes enclosed in the conditional block appear to continue to get processed and I get errors indicating such. For instance, surrounding an [AssemblyVersion(...)] within the conditional block appears to have no affect.

I can go into the details as to why we want to conditionally ignore the [AssemblyVersion(..)], but it's irrelevant. Any ideas?

like image 641
Sean Aitken Avatar asked Jun 11 '09 14:06

Sean Aitken


People also ask

What is conditional attributes?

A conditional attribute is a tag used to mark a method or class whose execution depends on the definition of preprocessing identifier. A conditional attribute indicates a condition to specify conditional compilation wherein methods are selectively called on the basis of definition of symbols.


1 Answers

This works correctly for me. In my AssemblyInfo.cs file, I have the following:

#if DEBUG
[assembly: AssemblyConfiguration("Debug")]
#else
[assembly: AssemblyConfiguration("Release")]
#endif

Looking at the compiled assembly in Reflector, I see the correct attributes.

You should make sure that your DEBUG symbol is only defined in the project properties and not any where else in your code as an actual #define DEBUG instruction. If you have it defined directly in code it will only be in effect for that file, not the entire project. Defining it in the project properties will cause it be in effect for the entire project.

like image 175
Scott Dorman Avatar answered Oct 05 '22 15:10

Scott Dorman