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 TEST constant is defined.

[Conditional("DIAG")]
[Conditional("TEST")]
private void Test()
{
MessageBox.Show("Test", "Test", MessageBoxButtons.OK);
}

To define a compilation constant, 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, Visual Basic still generates code for it and still checks the calling routine's parameters against those required by the method, but it does not perform the call at run time.

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

  

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.