TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

C# Conditional Method

This C# example program uses the Conditional attribute from System.Diagnostics.

Conditional. A Conditional method is not always executed.

It is compiled into the program only when certain symbols are defined with #define. The Conditional attribute enables this feature. It accepts a string literal as its argument.

Argument: The string argument is the text of the symbol that must be defined for the method to be compiled.

String Literal

Example. To start, this example program has two methods other than the Main entry point. It contains a MethodA, which is conditional on the symbol PERLS. It also contains MethodB, which is conditional on the symbol DOT.

At the top of the program, you can see two preprocessor directives. The symbol PERLS is defined. The symbol DOT is not. The execution of the program shows that MethodA is executed, but MethodB is not.

C# program that uses Conditional attribute

#define PERLS
#undef DOT
using System;
using System.Diagnostics;

class Program
{
    static void Main()
    {
	MethodA();
	MethodB();
    }

    [Conditional("PERLS")]
    static void MethodA()
    {
	Console.WriteLine(true);
    }

    [Conditional("DOT")]
    static void MethodB()
    {
	Console.WriteLine(false);
    }
}

Output

True

It isn't possible to use Conditional on methods that return a value. Methods must be used in the void context. This is because variables can be assigned to method return values. You can work around this limitation using parameters.

Void

Conditional List. Next, it is possible to modify a collection in only DEBUG mode. This way, you can add strings or other values to your array conditionally—when debugging your application, not when it's deployed. The Conditional attribute is ideal here.

List

DEBUG List:

rabbit
bird
cat
mouse

RELEASE List:

rabbit
bird

You can use clunky #if and #endif directives all over your code, but this is an eyesore and also prone to typos. Sometimes, developers will use Array.Copy and more error-prone code.

Here, we can use a Conditional attribute on a method. This indicates that the method be completely compiled out of the source when not in the Conditional mode. We add elements only in DEBUG mode.

Array.Copy

C# program that uses conditional method

using System;
using System.Collections.Generic;
using System.Diagnostics;

class Program
{
    static void Main()
    {
	List<string> l = new List<string>();
	l.Add("rabbit");
	l.Add("bird");
	AddToArray(l);
	Console.WriteLine("Elements: {0}",
	    l.Count);
	Console.Read();
    }

    [Conditional("DEBUG")]
    static void AddToArray(List<string> l)
    {
	// New array
	string[] a = new string[2];
	a[0] = "cat";
	a[1] = "mouse";
	// Add array to end of list
	l.AddRange(a);
    }
}

Output of the program in DEBUG

Elements: 4

Output of the program in RELEASE

Elements: 2

It defines an AddToArray method, which simply adds two elements to the array. It uses the Conditional("DEBUG") attribute. This means to only compile the method if DEBUG is defined. The Conditional attribute requires System.Diagnostics.

Reduce attack surface. Always disable DEBUG on deployed web sites and applications. This reduces the attack surface, as it removes many developer-specific knobs. The Conditional attribute is ideal for separating DEBUG logic.

Note: In the example, Main() doesn't know "cat" and "mouse" even exist. This clarifies the code.

You can encapsulate your DEBUG-specific logic in separate Conditional("DEBUG") methods. Don't let any debug logic slip into your release builds. This improves code clarity and performance, and reduces attack surface.

Summary. Conditional allows us to create a method whose existence depends on a preprocessor directive. Unlike using #ifdef directives the Conditional attribute fits with the clear syntax of the C# language.

Note: This syntax is more high-level, less lexical. It is a declarative programming pattern.

Thus: The Conditional attribute helps maintain descriptive and easy-to-maintain source code.


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf