C# Line Directive

This C# program demonstrates the #line preprocessing directive. This directive helps in code generators.

Line directive. The compiler reports the lines of errors.

The #line directive influences the current line reported. It is useful if you are generating C# code files, and want to retain the original code's line numbers.

 

 

Example. To begin, this program uses the #line directive in three different 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. The #line hidden command is used—this removes all line number information.

C# program that uses line directives

using System;

class Program
{
    static void Main()
    {
#line 999
	throw new Exception();
#line default
	throw new Exception();
#line hidden
	throw new Exception();
    }
}

Results
    (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. Why would you ever want to change line numbers in the preprocessor? 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 has a limited use in the C# language. But it 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.

 

And: If you need it, the line directive is useful. But in almost all programs, it is worthless.