The SLAR on System.Diagnostics.ConditionalAttribute

More from the series sharing some of the information in the .NET Framework Standard Library Annotated Reference Vol 1 here is an annotation and simple sample from the System.Diagnostics.ConditionalAttribute attribute.


Brad Abrams: There is a common misconception with usage of this custom attribute. By

applying the ConditionalAttribute on a method you indicate that calls to that

method should be removed by the compiler if the conditionString is defined.

However, the method body is always compiled into the assembly regardless of

whether the conditionString is defined or not.


Brian Grunkemeyer: This is another clever custom attribute, which works similarly to C-style preprocessor

directives but in reverse. Calls to methods with this attribute are conditionally

compiled into source code, depending on whether the given symbol is defined at

compile time. For debugging or tracing code, this means you simply add this attribute

to the method you want to call conditionally, instead of putting #if FOO … #endif

all throughout your code.


Jeffrey Richter The ConditionalAttribute can be applied to methods that return void only.

Note that any expressions that are evaluated when calling a conditional method are

not evaluated if the method is not called. For example, in the following code, Get-

String and Foo are not called if “xx” is not defined:

using System;

using System.Diagnostics;

class App


    static void Main()




    static String GetString() { return "Jeff"; }


    static void Foo(String s) { Console.WriteLine(s); }


If you examined the IL produced by the compiler for Main, you’d see that it contains

just one IL instruction: ret.




And here is a simple example:


#undef A

using System;

using System.Diagnostics;

namespace Samples


    public class MyClass



        public static void Display()


            Console.WriteLine("A was defined");



    public class ConditionalAttributeSample


        public static void Main()








The output is


Comments (4)

  1. Stu Smith says:

    Out of curiosity, why doesn’t this work in Managed C++ (VS2003)? Debug::Assert still fires in a release build.

Skip to main content