views:

247

answers:

1

I have a templating system that looks similar to old-style ASP code. I run this through a class that rewrites the entire thing into C# source code, compiles, and finally executes it.

What I'm wondering is if there is some kind of #pragma-like directive I can sprinkle the generated C# code with that will make compile errors match the line numbers in my template file?

For instance, let's say I have this first and only line in my template code:

Object o = datta; // should be data, compiler error

but then in order to compile this I must add a namespace, a class, a method, and some boiler-plate code to it, so this line above, which is line #1 in my template file, actually ends up being line #17 (random number, just for illustrative purposes) in the C# code. The compiler error will naturally flag my error as being on line #17, and not on line #1.

I remember from another programming language I've used before (though I can't remember which one) that it had a directive that I could add, which would make error line numbers line up.

Is there any such thing in C# 3.5?

+8  A: 

You have the #line preprocessor directive.

#line lets you modify the compiler's line number and (optionally) the file name output for errors and warnings.

The #line directive might be used in an automated, intermediate step in the build process. For example, if lines were removed from the original source code file, but you still wanted the compiler to generate output based on the original line numbering in the file, you could remove lines and then simulate the original line numbering with #line.

The #line hidden directive hides the successive lines from the debugger, such that when the developer steps through the code, any lines between a #line hidden and the next #line directive (assuming that it is not another #line hidden directive) will be stepped over. This option can also be used to allow ASP.NET to differentiate between user-defined and machine-generated code. Although ASP.NET is the primary consumer of this feature, it is likely that more source generators will make use of it.

A #line hidden directive does not affect file names or line numbers in error reporting. That is, if an error is encountered in a hidden block, the compiler will report the current file name and line number of the error.

The #line filename directive specifies the file name you want to appear in the compiler output. By default, the actual name of the source code file is used. The file name must be in double quotation marks ("") and must be preceded by a line number.

280Z28
+1, learn something new everyday
JaredPar
That was exactly what I needed! Thanks!
Lasse V. Karlsen
@Jared: I saw it one day looking through generated WPF code and was like. :hmm: :) It's what links errors to the originating XAML file.
280Z28