Compiler directives is always a fun for any language. There are lots of talks around different blogs on compiler directives but there are hardly any talks around my favorite #pragma
directives. So lets talk what it is and what it is capable of.
In general, Pragma directives are special instruction to the compiler when it compiles a file. Say for instance if you want to your function does not react to some of the warnings that compiler produces, you can use Pragma pre-processor directives.
.NET supports two types of Pragma
1. Pragma Warning
2. Pragma Checksum
Pragma Warning
Pragma warning allows you to disable / enable certain warnings that the compiler produces when certain code appears on your code.
For example :
private static void Main(string[] args) { int x = 10; }
Lets say I write this code. Now you must know, compiler will produce one warning for this code.
Now if you want to disable this warning for the code you write, you can wrap around your code in pragma statement like below :
private static void Main(string[] args) { # pragma warning disable 0219 int x = 10; #pragma warning restore 0219 }
And your warning will go away. You can specify multiple warning numbers in one pragma statement like :
# pragma warning disable 0219, 0329, 3193
If you put any wrong number in the warning list, the compiler will just ignore that.
Now, one question might come to your mind, where do I get this numbers. When you build your project, just see the output window, it will say the number in it as shown in the figure.
When you compile your code, you will get the warning numbers before the actual warning in the output window. Just remove the CS in the string to get the actual warning number.
Pragma Checksum
Checksum is a special number that identifies a file. The .NET debugger generates a checksum of a file and puts in Program Database(PDB file) when it compiles. Hence even though your file is modified when you run, the checksum will always point to right source.
In case of ASP.NET, the computed checksum that is produced in the PDF file is actually points to the one that is generated rather than the actual source. You can use Pragma statement in your asp.net file to generate new checksum for your file.
#pragma checksum "yourfile.cs" "{3673e4ca-6098-4ec1-890f-8fceb2a794a2}" "{012345678AB}"
This generates a new Checksum for the file yourfile.cs and the new checksum will be written to the PDB it generates.
Remember, the hexadecimal value you pass as last argument in #pragma checksum directive should be even, any odd checksum byte will be ignored by the compiler.
Compiler directive #Pragma reference | Daily .NET Tips