tags:

views:

1337

answers:

4

Does anyone has a good solution for a C# version of the C++ __FUNCTION__ macro? The compiler does not seem to like it.

+5  A: 

Try using this instead.

System.Reflection.MethodBase.GetCurrentMethod().Name

C# doesn't have __LINE__ or __FUNCTION__ macros like C++ but there are equivalents

Eoin Campbell
Ruben Bartelink
+4  A: 

The following should work, although it will be evaluated at runtime instead of during compilation.

System.Reflection.MethodBase.GetCurrentMethod().Name
e.James
+2  A: 

Unfortunately there is no equivalent version of that macro in C#. I don't consider the GetCurrentMethodName() solution equivalent to the C++ __FUNCTION__ macro. Namely becase the C++ version is a compile time computation of the name. For C# this is a runtime calculation and incurs a performance hit.

I'm not making any assumtions about the severity of the cost but there is one

JaredPar
True, it would be nice to have a compile-time solution.For my purpose reflection is quite sufficient.
Filip
+1  A: 

What I currently use is a function like this:

using System.Diagnostics;

public string __Function() {
    StackTrace stackTrace = new StackTrace();
    return stackTrace.GetFrame(1).GetMethod().Name;
}

When I need __FUNCTION__, I just call the __Function() instead. For example:

Debug.Assert(false, __Function() + ": Unhandled option");

Of course this solution uses reflection too, but it is the best option I can find. Since I only use it for Debugging (not Tracing in release builds) the performance hit is not important.

I guess what I should do is create debug functions and tag them with

[ Conditional("Debug") ]

instead, but I haven't got around to that.

Thanks to Jeff Mastry for his solution to this.

Mark Booth