Comparing Conditional Attributes In C/C++ versus C#

Introduction

I am a C++ programmer, but today I am assigned to a C# project, and I found an article on your site. However, I guess the article is inaccurate and hides information. The author may have tried to expose the beauties of C# by fading others' features. The intention should never be to compare languages because each has its own features that the other does not have. However, C++ compilers have improved too much during the last 20 years, and language has become mature.

(taken from http://www.c-sharpcorner.com/Effectivecs/DebugTechniquesMB001.asp).

[Conditional("DEBUG")]
public void Debug(string msg)
{
    // This is where the debug statement display code would be
}

This will do when this program is compiled, it will check if DEBUG was #defined, and if it was, then the call to this function will remain; however, if DEBUG is not #defined, all calls to this function not will be compiled leaving us with no performance hit.

Now, some of you may probably say that you could solve some of the problems above in C/C++ and Java. I will note that neither language solves all of them. For example, in C/C++, you can #define and #ifdef much like you can use the ConditionalAttribute class and C# defines. However, getting useful meta-information in C/C++ is limited. In Java, getting meta-information is possible, but as far as I know, all the code is always compiled (i.e., there's no Conditional type functionality).

Thankfully there is C# which does solve (gracefully, I might add) all the problems I mentioned above and quite a few more.

Yes, I claim "I can do even better with C++". meta-information is totally useless; it is garbage in our metadata. What would I do with this metadata on the final release?

The author hides a fact. Conditional attribute class cannot be used inside a method. that is

private void f()
{
    // Do something
    // [Conditional("condition1")] // Error! Conditional attribute cannot be applied here
    // Do something else
}

but C++ does.

private:
    void f()
    {
#ifdef condition1
        /* Code to execute when condition1 is defined */
        /* ... */
#else
        /* Code to execute when condition1 is not defined */
        /* ... */
#endif
    }

C++ (or C) can do this.

const char g_szText[] = "HELLO "
#ifdef condition1
"CONDITION1"
#else
"SOME OTHER CONDITION"
#endif
;

you can do even more crazy stuff.

ConditionalAttribute has a quite smaller scope/use than C's #ifdef preprocessor directives. because when we build, that means we already know enough about the target and the code that we should generate. so meta-information becomes useless. for debugging, we have a trace facility. if you insist, in C++, you can place metainfo explicitly by preprocessor directives again (into an executable file, not much like metadata).

This is just a correction with no insult intended.


Recommended Free Ebook
Similar Articles