Is there a C # equivalent for C ++ macros __FILE__, __LINE__ and __FUNCTION__?

I have C ++ code that I am trying to port to C #. There, in C ++, I used the following macro 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 constructions in C #? I know there are no macros in C #, but is there any other way to get the current values โ€‹โ€‹of a file, line and function at runtime?

+7
source share
3 answers

If you are using .net 4.5, you can use the CallerMemberName CallerFilePath CallerLineNumber attributes to get these 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 an outdated framework and visual 2012, you just need to declare them as they are in the framework (same namespace) to make them work.

+11
source

I think StackFrame is exactly what you are looking for.

+4
source

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

+3
source

All Articles