BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

C# Programming
.NET 1.1+

C# #line Directive

When you compile and execute C# code, errors and warnings may be generated with a reference to a source code file and line number. If you develop a tool that creates the code to be compiled, you may want to change the reported error locations.

Metaprogramming Tools

A metaprogramming tool is a software application that generates or manipulates other programs or code. An example of such a program is a computer aided software engineering (CASE) tool that allows C# software to be developed using a combination of diagramming and coding of small functions.

In such a tool, the source diagrams and code will be named and code may include line numbers. However, once the diagrams and functions are combined into the target program, the final file names and line numbers will probably be different to those referred to in the CASE tool. This can cause a problem when the C# code is compiled and any compiler warnings or errors refer to locations that the user has never seen.

#line Directive

The #line compiler directive helps you to overcome the above problem. When included in a C# source code file, the line numbering can be reset at any point and the name of the file reported in errors can be changed. The names and line numbers that you specify can be configured to represent locations in the original CASE tool files.

The following code is a sample that could have been generated by a CASE tool. In the code, two classes have been generated, using information from UML diagrams. To allow the line numbers in warnings and errors to be reported in a useful fashion, the #line directive has been used to set the line number and the name of the source diagram file. The two #warning directives are included in the code so that the compiler outputs warnings with the desired location details.

On compiling the code, one warning is displayed for line 5 of the file, "Program.uml". A second warning is recorded for line 3 of the file, "Car.uml".

namespace ConsoleApplication1
{
#line 1 "Program.uml"
    class Program
    {
        static void Main(string[] args)
        {
#warning Compiler Warning
        }
    }

#line 1 "Car.uml"
    class Car
    {
#warning Compiler Warning
    }
}
12 August 2008