Understanding #line directive

Asked

Viewed 106 times

2

I’m trying to understand the directive #line. I read in that documentation and I was able to understand the applicability of #line hidden but not that of #line [any_numer].

Taking as example a file App.g.i.cs what is doing the following code snippet in the method InitializeComponent():

#line 5 "..\..\App.xaml"
this.Startup += new System.Windows.StartupEventHandler(this.Application_Start);

#line default
#line hidden

1 answer

3


Are you saying that the code this.Startup += new System.Windows.StartupEventHandler(this.Application_Start); will appear as being on line 5 in the file ..\..\App.xaml, no matter which line is actually in the file, or in which file. Then it goes back to normal numbering.

Any error or warning the compiler issues will have this information. At the time of debugging the code will show this as well.

Its use is very rare and almost always linked to code generators. This is usually required when the code is produced by some generator and not written by the programmer. It may contain some things that need to be shown to the programmer differently from what is actually presented, even hidden. Without it some information would be strange or misleading.

It is also used in meta-programming, something that is still little encouraged in C# (tends to be used more, is the future of programming for some things). But it’s a much more advanced topic. The reason it’s not mainstream is that few programmers can do it right. How this paradigm usually generates a lot of code is a means of informing a line number that makes sense to the programmer who usually only sees the written code and not the generated code, which obviously changes the numbering of the lines.

Almost no one needs to know this, but it is a useful resource for the cases cited.

  • It’s roughly telling the compiler to consider that a given line has such code, even if physically it’s not there, i.e."- Compile whereas on the line X exists the code Z". Would that be it? Interesting, I use meta-programming in Python to validate data, is one of the tricks that Python has to get rid of getters and setters, but obviously because python is dynamic it is much easier to handle meta-programming.

  • 1

    More or less that. There are several ways to use. The normal is for the compiler to count the lines according to the text file, using this feature you tell what line you want the compiler to consider there. You can do a lot of damage with it. Of course the number for compilation effect doesn’t change anything, but as information for you changes a lot. Meta-programming in static language is much more complicated, in an extensive language like C#, even worse.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.