2

I know what ConditionalAttribute does.

The docs say it can also be applied to a class, if it's derived from Attribute:

[Conditional("DEBUG")]
public class FooAttribute : Attribute { }

But how does that custom attribute behave? (Is it stripped out of a release build?)

h bob
  • 3,610
  • 3
  • 35
  • 51
  • There's another question about: http://stackoverflow.com/a/1412838/4730201 – Ricardo Pontual Aug 16 '16 at 19:04
  • @RicardoPontual No that doesn't address the issue. I want to know what it does when applied to an `Attribute` specifically. – h bob Aug 16 '16 at 19:34
  • [Applying ConditionalAttribute to an attribute indicates that the attribute should not be emitted to metadata unless the conditional compilation symbol is defined.](http://msdn.microsoft.com/en-us/library/system.diagnostics.conditionalattribute(v=vs.110).aspx) What does that mean?? – h bob Aug 16 '16 at 19:35
  • Interesting.. what I could understand is that the attribute is omitted, like it does not exists in class. Some tests can confirm that. – Ricardo Pontual Aug 16 '16 at 19:52
  • @RicardoPontual How did you test? Thanks for the idea, check my answer. – h bob Aug 17 '16 at 07:17

1 Answers1

2

@RicardoPontual's comment gave me an idea.

I did this:

[Conditional("DEBUG")]
public class FooAttribute : Attribute { }

[Foo]
public class Bar { }

I compiled in debug mode, and loaded the DLL in ILSpy (it's a disassembler). This is what I found, as expected:

[Foo]
public class Bar { }

Then I compiled in release mode, and loaded that DLL in ILSpy. This is what I found:

public class Bar { }

The Bar class was not decorated this time!

So, the answer is that when you decorate some custom attribute with Conditional, then that attribute itself becomes conditional in the same way.

That's the behavior I wanted. I initially thought to derive from ConditionalAttribute, but it's sealed. Instead you need to decorate your custom attribute.

h bob
  • 3,610
  • 3
  • 35
  • 51
  • 1
    Great, the test answered the question. I could imagine some useful things, like implement a logic in runtime depending on whether the assembly was compiled debug or release, just inspecting the presence of a custom attribute: `if (typeof(MyType).IsDefined(typeof(MyCustomAttribute), false))` – Ricardo Pontual Aug 17 '16 at 11:34