What is the reason behind using the #line directive in c# to change the error or warning's default line number?

Viewed 994

I was reading the Microsoft webpage https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/preprocessor-directives/preprocessor-line about #line directives in C#. It explains that the #line 200 directive forces the next line's number to be 200 (although the default is #6) until the #line default directive that returns the line numbering to its default numbering.

My question is why on the earth we would need to change the line number for an error or warning in our code?

class MainClass
{
    static void Main()
    {
#line 200 "Special"
        int i;
        int j;
#line default
        char c;
        float f;
#line hidden // numbering not affected
        string s;
        double d;
    }
}

Compilation produces the following output:

Special(200,13): warning CS0168: The variable 'i' is declared but never used
Special(201,13): warning CS0168: The variable 'j' is declared but never used
MainClass.cs(9,14): warning CS0168: The variable 'c' is declared but never used
MainClass.cs(10,15): warning CS0168: The variable 'f' is declared but never used
MainClass.cs(12,16): warning CS0168: The variable 's' is declared but never used
MainClass.cs(13,16): warning CS0168: The variable 'd' is declared but never used
1 Answers

There are a number of scenarios where this directive is useful, most of them never seen by most C# developers.

All of the scenarios I'm aware of involve a C# file that is either generated or modified by some other process, and the #line directive is used to make sure that the .pdb information for the compiled version of the file provides accurate information relative to the original input.

The documentation page you've been referred to alludes to this with their example. They imagine a build step that deletes (removes) lines from an original C# file before the result is compiled. Someone trying to debug that code would have difficulty if the debugging information showed the processed line numbers rather than the original line numbers, since when they are debugging they likely will be looking at the original authored file, not the modified pre-processed file.

Other examples I'm aware of include the output of T4 processing, and the C# files generated when compiling XAML files. In these cases, there is no original C# file, but there is an original authored file, and if there's an exception or other reason to convey the line number to someone trying to debug the code, they will want to know the line number from the original file, not the generated file that they likely would never see.

Related