I use the following statement to print the name of the current function (for example, an event handler) to the Output window in Visual Studio (2010):
Debug.Write(MethodBase.GetCurrentMethod().Name);
If I put this inside a utility function such as DisplayFunctionName()
, instead of the parent function that calls it, what is displayed each time is "DisplayFunctionName
" - no surprises there!
I know there is no inlining in C#, but is there another solution for this situation, short of using 'snippets', so as not to have to duplicate such statements?
You can use the CallerMemberNameAttribute
to display the caller's name.
public void WriteDebug(string message, [CallerMemberName] string memberName = "")
{
Debug.Write("[" + memberName + "] " + message);
}
There is also CallerLineNumberAttribute
and CallerFilePathAttribute
which you can use to include this information for more diagnostics. These attributes are described in detail on MSDN. Combined with [Conditional("DEBUG")]
on the method, you have the capability to provide a lot of information during debugging that is completely eliminated in a release build.
I know there is no inlining in C#, but is there another solution for this situation, short of using 'snippets', so as not to have to duplicate such statements?
Note that this really has nothing to do directly with "inlining", as much as with getting the calling member's information for diagnostics. That being said, the JIT definitely performs inlining when your code is run, which is one of the major reasons C# has decent performance.
This requires Visual Studio 2012, as it uses new compiler features in that release to function.
If you are using an older compiler, the other alternative is to use StackTrace
to pull out the stack trace information. This has a fairly significant performance impact, however, so it's not something I'd use in a tight loop, at least not in a production environment, though its still functional for diagnostics during debugging.
string callingMethodName = (new StackTrace()).GetFrame(1).GetMethod().Name;