9

I have a C++ code that I'm trying to migrate to C#. Over there, on C++, i was using the following macros definition for debugging purposes.

#define CODE_LOCATION(FILE_NAME, LINE_NUM, FUNC_NAME) LINE_NUM, FILE_NAME, FUNC_NAME
#define __CODE_LOCATION__ CODE_LOCATION(__FILE__, __LINE__, __FUNCTION__)

Are there similar constructs in C#? I know there are no macros in C#, but is there any other way to get the current file, line and function values during execution?

Martin Liversage
  • 104,481
  • 22
  • 209
  • 256
NirMH
  • 4,769
  • 3
  • 44
  • 69
  • Possible duplicate of [Do \_\_LINE\_\_ \_\_FILE\_\_ equivalents exist in C#?](http://stackoverflow.com/questions/696218/do-line-file-equivalents-exist-in-c) – Jim Fell May 10 '16 at 18:32
  • @JimFell: while this question was posted 3 years ago and the duplicate is dated 7 years ago, i think it doesn't matter :) - both answers provide the solution - might worth merging the answers... – NirMH May 11 '16 at 06:41

3 Answers3

14

If you are using .net 4.5 you can use CallerMemberName CallerFilePath CallerLineNumber attributes to retrieve this values.

public void DoProcessing()
{
    TraceMessage("Something happened.");
}

public void TraceMessage(string message,
    [CallerMemberName] string memberName = "",
    [CallerFilePath] string sourceFilePath = "",
    [CallerLineNumber] int sourceLineNumber = 0)
{
    Trace.WriteLine("message: " + message);
    Trace.WriteLine("member name: " + memberName);
    Trace.WriteLine("source file path: " + sourceFilePath);
    Trace.WriteLine("source line number: " + sourceLineNumber);
}

If you are using older framework and visual 2012 you just need to declare them as they are in framework (same namespace) to make them work.

Rafal
  • 12,391
  • 32
  • 54
4

I guess StackFrame is exactly what you're looking for.

Pang
  • 9,564
  • 146
  • 81
  • 122
Mario
  • 35,726
  • 5
  • 62
  • 78
  • 2
    it only works in Debug builds. In a production Release build, the file name and line number information doesn't exist. Also, the StackFrame object may be null in a release build, which would NullReferenceException to be thrown at runtime. – Hossein Oct 07 '14 at 02:37
3

In .NET 4.5 there is a set of new attributes that you can use for this purpose: Caller Information

Peter
  • 346
  • 5
  • 7