In Visual Stuido 2013, working in C# (.Net 4.5), how can I pass a line number to a method call. I recall in C there was a #pragma lineNumber to do this, but searching on those terms brings up nothing.
I want to write a method something like this:
// unchecked code:
private void printResetStopwatch(int lineNumber)
{
stopwatch.stop();
System.Console.WriteLine(stopwatch.Elapsed.ToString() + " at line " + lineNumber.ToString();
}
and I would call it something like
printResetStopwatch(#pragma lineNumber);
if #pragma was the answer.
The way to do this is to attribute a parameter on the method with the CallerLineNumberAttribute
and provide it with a default value. C# will then fill it in with the line number of the caller
void Method(string message, [CallerLineNumber] int lineNumber = 0) {
...
}
Method("foo"); // C# will insert the line number here
Note that there are actually a set of related attributes here that might interest you. Here is a sample
public void TraceMessage(string message,
[CallerMemberName] string memberName = "",
[CallerFilePath] string sourceFilePath = "",
[CallerLineNumber] int sourceLineNumber = 0)
Full Documentation: http://msdn.microsoft.com/en-us/library/hh534540.aspx
Note: This requires the C# 5.0 compiler which is included in VS 2013.