Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make conditional attributes in C#?

Tags:

c#

attributes

I want to hide some member vars in my C# class.
I can do this via the DebuggerBrowsable attribute:

using System.Diagnostics;

[DebuggerBrowsable(System.Diagnostics.DebuggerBrowsableState.Never)]
int myvar;

However, I only want this attribute to be applied for Release builds - I want to hide the var from my assembly's Release-build consumers but I want the var visible in Debug builds for inspection during dev, etc.

I could, but would prefer not to, wrap each attribute in an #if block:

#if !DEBUG
        [DebuggerBrowsable(System.Diagnostics.DebuggerBrowsableState.Never)]
#endif

That would do the trick, but creates some pretty messy-looking code.

If I were in C++/CLI - and had macros - I could do this:

#ifdef _DEBUG
#define HIDDEN_MEMBER
#else
#define HIDDEN_MEMBER   [System::Diagnostics::DebuggerBrowsableAttribute(System::Diagnostics::DebuggerBrowsableState::Never)]
#endif

and then

HIDDEN_MEMBER
int myvar;

But no macros in C# :(

Any bright ideas as to how to achieve the macro-like syntax in C#?

like image 209
dlchambers Avatar asked Feb 15 '26 07:02

dlchambers


1 Answers

See the ConditionalAttribute class, you can apply the [Conditional] attribute to the [DebuggerBrowsable] attribute.

like image 74
Tony Basile Avatar answered Feb 17 '26 19:02

Tony Basile