[C# Helper]
Index Books FAQ Contact About Rod
[Beginning Database Design Solutions, Second Edition]

[Beginning Software Engineering, Second Edition]

[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

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

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

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 the example to experiment with it and to see additional details.

© 2009-2023 Rocky Mountain Computer Consulting, Inc. All rights reserved.