Click here to Skip to main content
15,885,365 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
Hi,

I have been experimenting with getting code to be excluded by use of the Conditional attribute. The code I have been using couldn't be simpler, and is as follows:


class Program
{
	static void Main( string[] args )
	{
		CallFunction();
	}

	[Conditional("TEST_SYMBOL")]
	static void CallFunction()
	{
		int x = 1; 
		int y = 1; 
		_z = x - y;
		_z /= _z;
	}
		
	private static int _z = 0;
}


When I build and run the application with TEST_SYMBOL defined, I get the expected divide-by-zero error, and when the symbol is not defined, I get no error. So far so good.

But when I examine the compiled assemblies on disk (with and without the symbol defined), both are exactly the same number of bytes; and when I examine them with Reflector, the code in CallFunction() appears to be present in both assemblies.

My understanding was that the Conditional attribute allowed code, not just to be called or not called, but also to be excluded if unused. Otherwise, it is just unnecessary code bloat in one of the assemblies.

Am I missing something here? Any help would be very much appreciated.

Best wishes, Patrick
Posted
Comments
Estys 14-Jul-10 6:03am    
Reason for my vote of 5
Excellent question, this has given me an opportunity to broaden my knowledge.

Read this article : http://www.blackwasp.co.uk/ConditionalMethods.aspx[^]
I quote :
"This key difference has benefits and drawbacks. The obvious drawback is that the compiled assembly will be larger than if the conditional method were not included. The main benefit is that the assembly can be shared between programs and libraries. Each of these may be compiled with different compiler symbols defined. This means that a single assembly can behave differently according to the program calling it. Another benefit is that the main code of the program is seen by some as more elegant without the #if and #endif conditions."


Cheers
 
Share this answer
 
If you want the code to be smaller, you have to use #if/#endif to define compiler directives. What you've done in the code above will still include the method in the compiled assembly, but will only expose it to assemblies (or code) that has the specific compiler definition defined.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900