Line directive. The compiler reports the lines of errors. The #line directive influences the current line reported. This directive is not often useful.
Some uses. It is useful if you are generating C# code files, and want to retain the original code's line numbers. But for most C# developers "line" is never used.
Example. To begin, this program uses the #line directive in 3 ways. The first usage specifies an integer after #line. This changes the line number of the line immediately following the directive.
Also The #line default command is used. This changes the line numbers to how they would be if no #line directives were present.
Tip The #line hidden command is used—this removes all line number information.
using System;
class Program
{
static void Main()
{
#line 999
throw new Exception();
#line default
throw new Exception();
#line hidden
throw new Exception();
}
}(Comment out first two exceptions to skip them.)
Unhandled Exception: ...Program.cs:line 999
Unhandled Exception: ...Program.cs:line 10
Unhandled Exception: ...Program.cs:line 0
Discussion. The main use would be if you wrote another program that changed a C# source file in some way. It might add more code in a specific spot and remove it elsewhere.
Tip You could inject #line directives to make exceptions report errors in the correct locations in the original (not generated) code.
Summary. The #line directive provides a piece of functionality that could occasionally improve the clarity of programs. It is mainly useful if you are doing advanced meta-programming work.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Apr 7, 2022 (rewrite).