Chapter93:Preprocessordirectives

No Comments

Section93.1:ConditionalExpressions

Whenthefollowingiscompiled,itwillreturnadifferentvaluedependingonwhichdirectivesaredefined.

//Compilewith/d:Aor/d:Btoseethedifference

stringSomeFunction()

{

#ifA

return”A”;

#elifB

return”B”;

#else

return”C”;

#endif

}

Conditionalexpressionsaretypicallyusedtologadditionalinformationfordebugbuilds.

voidSomeFunc()

{

try

{

SomeRiskyMethod();

}

catch(ArgumentExceptionex)

{

#ifDEBUG

log.Error(“SomeFunc”,ex); #endif

HandleException(ex);

}

}

Section93.2:OtherCompilerInstructions

Line

#linecontrolsthelinenumberandfilenamereportedbythecompilerwhenoutputtingwarningsanderrors.

voidTest()

{

#line42″Answer”

#linefilename”SomeFile.cs”

intlife;//compilerwarningCS0168in”SomeFile.cs”atLine42

#linedefault

//compilerwarningsresettodefault

}

PragmaChecksum

#pragmachecksumallowsthespecificationofaspecificchecksumforageneratedprogramdatabase(PDB)for debugging.

#pragmachecksum”MyCode.cs””{00000000-0000-0000-0000-000000000000}””{0123456789A}”

Section93.3:DefiningandUndefiningSymbols

A compiler symbol is a keyword that is defined at compile-time that can be checked for to conditionally execute specific sections of code.

Therearethreewaystodefineacompilersymbol.Theycanbedefinedviacode:

#defineMYSYMBOL

TheycanbedefinedinVisualStudio,underProjectProperties>Build>ConditionalCompilationSymbols:

(NotethatDEBUGandTRACEhavetheirowncheckboxesanddonotneedtobespecifiedexplicitly.)

Ortheycanbedefinedatcompile-timeusingthe/define:[name]switchontheC#compiler,csc.exe. Youcanalsoundefinedsymbolsusingthe#undefinedirective.

ThemostprevalentexampleofthisistheDEBUGsymbol,whichgetsdefinedbyVisualStudiowhenanapplicationis compiled in Debug mode (versus Release mode).

publicvoidDoBusinessLogic()

{

try

{

AuthenticateUser();

LoadAccount();

ProcessAccount();

FinalizeTransaction();

}

catch(Exceptionex)

{#ifD

EBUG

System.Diagnostics.Trace.WriteLine(“Unhandledexception!”); System.Diagnostics.Trace.WriteLine(ex);

throw;

#else

LoggingFramework.LogError(ex);

DisplayFriendlyErrorMessage();

#endif

}

}

In the example above, when an error occurs in the business logic of the application, if the application is compiled in Debug mode (and the DEBUGsymbol is set), the error will be written to the trace log, and the exception will be re-

thrownfordebugging.However,iftheapplicationiscompiledinReleasemode(andnoDEBUGsymbolisset),a logging framework is used to quietly log the error, and a friendly error message is displayed to the end user.

Section93.4:RegionBlocks

Use#regionand#endregiontodefineacollapsiblecoderegion.

#regionEventHandlers

publicvoidButton_Click(objects,EventArgse)

{

//

}

publicvoidDropDown_SelectedIndexChanged(objects,EventArgse)

{

//

}

#endregion

ThesedirectivesareonlybeneficialwhenanIDEthatsupportscollapsibleregions(suchasVisualStudio)isusedto edit the code.

Section93.5:DisablingandRestoringCompilerWarnings

Youcandisablecompilerwarningsusing#pragmawarningdisableandrestorethemusing#pragmawarningrestore:

#pragmawarningdisableCS0168

//Willnotgeneratethe”unusedvariable”compilerwarningsinceitwasdisabled

varx=5;

#pragmawarningrestoreCS0168

//Willgenerateacompilerwarningsincethewarningwasjustrestored

vary=8;

Comma-separatedwarningnumbersareallowed:

#pragmawarningdisableCS0168,CS0219

TheCSprefixisoptional,andcanevenbeintermixed(thoughthisisnotabest practice):

#pragmawarningdisable0168,0219,CS0414

Section93.6:GeneratingCompilerWarningsandErrors

Compilerwarningscanbegeneratedusingthe#warningdirective,anderrorscanlikewisebegeneratedusingthe

#errordirective.

#ifSOME_SYMBOL

#errorThisisacompilerError.

#elifSOME_OTHER_SYMBOL

#warningThisisacompilerWarning.

#endif

Section93.7:CustomPreprocessorsatprojectlevel

It is convenient to set custom conditional preprocessing at project level when some actions need to be skipped lets say for tests.

GotoSolutionExplorer->Click                                 onprojectyouwanttosetvariableto->Properties->Build->

InGeneralfindfieldConditionalcompilationsymbolsandenteryourconditionalvariablehere

Codeexamplethatwillskipsomecode:

publicvoidInit()

{

#if!IGNOREREFRESHDB

//willskipcodehere

db.Initialize();#endif

}

Section93.8:UsingtheConditionalattribute

Adding a Conditionalattribute from System.Diagnosticsnamespace to a method is a clean way to control which methodsarecalledinyourbuildsandwhicharenot.

#defineEXAMPLE_A

usingSystem.Diagnostics;

classProgram

{

staticvoidMain()

{

ExampleA();//Thismethodwillbecalled

ExampleB();//Thismethodwillnotbecalled

}

[Conditional(“EXAMPLE_A”)]

static void ExampleA() {…}

[Conditional(“EXAMPLE_B”)]

static void ExampleB() {…}

}

About us and this blog

We are a digital marketing company with a focus on helping our customers achieve great results across several key areas.

Request a free quote

We offer professional SEO services that help websites increase their organic search score drastically in order to compete for the highest rankings even when it comes to highly competitive keywords.

Subscribe to our newsletter!

More from our blog

See all posts
No Comments

Recent Posts

Leave a Comment