Yes this is possible, however this requires access to the sourcefile, if you
really need the sourcecode.
Use the CallerInformationAttributes
C# 4.5 Required:
int _beginIndex;
public void BeginTrace(
[CallerFilePath] string sourceFilePath = "",
[CallerLineNumber] int sourceLineNumber = 0)
{
_beginIndex = sourceLineNumber;
}
public void EndTrace(
[CallerFilePath] string sourceFilePath = "",
[CallerLineNumber] int sourceLineNumber = 0)
{
int index = 0;
foreach(var line in File.ReadLines(sourceFilePath))
{
if(index++ > _beginIndex && index <sourceLineNumber)
Console.WriteLine(line);
}
}
Then use it like this:
BeginTrace();
Foo foo = new Foo();
foo.DoSomeStuff();
foo.Bar();
EndTrace();
This example only works with Begin and End in the same File though, aynthing else will be really hard to accomplish unless you pass some object arround...