line keyword in CSharp

I was working on some WPF code today and ended up looking in the partial class generated for a UserControl I was working on. The code it was generating was very strange and littered throughout it were some #line statements. So I headed over to the #line MSDN article to see what it was all about. It turns out it is a way for you to tell the compiler, directly in your code, to pretend that a particular line of code is actually from somewhere else. You can also “hide” code from the debugger apparently.

From what I understand this is only useful for compile time errors, and even then probably only useful for code generation. I’m pretty excited about this though because it will really be useful for generating code in NBusiness. In this way if I generate a property (for example) based on a field declared in an entity I can add a #line statement to redirect any errors that come up back to the entity field rather than some murky, generated, partial class that no one want’s to look through.

Beyond uses for code generation I really have a hard time coming up with a practical reason why it would be used… but it seems like it could be a really fun way to obfuscate code and make your coworkers life a living hell. Maybe if you don’t like a particular piece of code they wrote in, say, GiantComponenent.cs just add a snippet to one of your classes such as:

#line 1 "GiantComponent.cs"
)()F@#K@N3fkn

 

Now just head over to their desk and complain about some compile error you’re running into in their code.

Well I guess it’s true that you learn something new everyday.

Author: justinmchase

I'm a Software Developer from Minnesota.

Leave a Reply

Discover more from justinmchase

Subscribe now to keep reading and get access to the full archive.

Continue reading