AOP with Roslyn–part 5 – getting line number right
There is a problem with inserting lines – the number of lines is not the same. What I mean by this?
Look at this example
using System; namespace Test1 { class Program { static void Main(string[] args) { var dt=DateTime.Now; } } }
The DateTime.Now is on line 8
When we insert lines before and after each method, the DateTime.Now is on line 9
using System; namespace Test1 { class Program { static void Main(string[] args) { Console.WriteLine(" + "\"start Program_Main_6\"" + @"); var dt = DateTime.Now; Console.WriteLine(" + "\"end Program_Main_6\"" + @"); } } }
This is usually not so important – until you think about exception and stack trace. If we are moving the number of lines like so, the stack trace that will be raised by the program will make no sense to the programmer that grabs the code from the source control. More, the problem is aggravating with each method – so, if you have 30 methods in a file(I exaggerate a bit ) the number of lines will be increased with 30 for the last method. For others , will be with 29, 28 and so on, until the first method.
Fortunately, there is a solution – the #line directive.
See https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/preprocessor-directives/preprocessor-line and https://blogs.msdn.microsoft.com/abhinaba/2005/10/10/c-fun-with-line-directive/
So, what we need is to generate the #line <number> directive.