NirMH
NirMH

Reputation: 4929

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

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?

Upvotes: 9

Views: 6236

Answers (3)

Mario
Mario

Reputation: 36487

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

Upvotes: 4

Rafal
Rafal

Reputation: 12619

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.

Upvotes: 14

Peter
Peter

Reputation: 356

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

Upvotes: 3

Related Questions