C# Line Directive

Pound (#) symbol

#line influences the compiler's reporting of the current line. It is useful if you are generating C# code files, and want to retain the original code's line numbers—despite there being a different number of lines in some places.

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. The #line default command is also 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, which results in line 0 being reported.

This C# program demonstrates the #line preprocessing directive.

Program that uses #line directives [C#]

using System;

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

Result
    (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

Why?

Question and answer

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. You could inject #line directives to make exceptions report errors in the correct locations in the original code, not the generated code that is actually executed.

Summary

The C# programming language

The #line directive has a limited use in the C# language, but 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 where you have a program that injects C# code into existing code.

Directives
.NET