Tim
Tim

Reputation: 2911

Compiling of a Conditional Attribute

I've been reading about conditional attributes, and I am still a bit confused as to what happens at compile time. Say I have the following code:

[System.Diagnostics.Conditional("FLAG")]
private void DoSomething(string myString)
{
    //  Do Something
}

public void Foo()
{
    DoSomething("With this.");
}

Assume that FLAG is not defined. When compiled, will the DoSomething method be a part of the assembly, or will it not exist? Assuming it does exist, will the call to DoSomething be commented out (or removed from the assembly), or will it call the DoSomething method and see that it is conditional and the condition has not been met so return immediately?

Obviously jumping to the method and returning without running would take more cycles than never calling it. This would not be an issue in most cases, but still seems like something worth knowing.

Upvotes: 0

Views: 322

Answers (1)

BartoszKP
BartoszKP

Reputation: 35921

From the documentation (emphasis and omission mine):

Applying ConditionalAttribute to a method indicates to compilers that a call to the method should not be compiled into Microsoft intermediate language (MSIL) unless the conditional compilation symbol that is associated with ConditionalAttribute is defined. You will get a compilation error in Visual Studio if you apply this attribute to a method that does not return void. [...]

So effectively, the call will disappear from the resulting binary.

Also:

Any arguments passed to the method or attribute are still type-checked by the compiler.

Upvotes: 1

Related Questions