0

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.

philologon
  • 2,093
  • 4
  • 19
  • 35
  • 1
    http://stackoverflow.com/questions/12556767/how-to-get-current-line-number-for-example-use-at-messagebox-show – Ivarpoiss Mar 16 '14 at 02:15
  • This answers it. Thanks a bunch. Promote this to an answer, if you would, so I can mark it as accepted. – philologon Mar 16 '14 at 02:18
  • It would just be duplicate content. That answer can be easily found. – Ivarpoiss Mar 16 '14 at 02:22
  • It wasn't easy for me. I looked several minutes and never found it. I was using the wrong terminology, so s/o autosearch did not help me in this case. – philologon Mar 16 '14 at 02:35
  • Try google next time. Possibly using site:stackoverflow.com too. SO's search is very naive and sucks big time. – Ivarpoiss Mar 16 '14 at 02:39

1 Answers1

1

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.

JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
  • Note that this requires the new C# 5 compiler and .NET 4.5. You can get by with some fake attributes, but you do need the new compiler. – Lasse V. Karlsen Mar 16 '14 at 15:45