Use the Conditional attribute to make a method non-callable in C#

[conditional]

The Conditional attribute makes a method callable depending on whether a compile-time constant is defined. If the constant is not defined, then the compiler ignores calls to that method.

The following code makes the Test subroutine callable if either the DIAG or the TEST constant is defined.

using System.Diagnostics;
...
[Conditional("DIAG")]
[Conditional("TEST")]
private void Test()
{
    MessageBox.Show("Test");
}

You can use the #define directive at the top of the code to define a compilation constant as in the following statement.

#define TEST

Alternatively you can open the Project menu, select Properties, click the Build tab, and enter DIAG or TEST in the “Conditional compilation constants” box.

If a method is not callable, C# still generates code for it and still checks the calling code’s parameters against those required by the method, but it does not call the method at run time.

You can use #if to exclude code from compilation but if you exclude a method in that way, any code that calls the method will generate an error. Using Conditional allows you to hide a method more easily.


Download Example   Follow me on Twitter   RSS feed   Donate




This entry was posted in attributes, debugging and tagged , , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *