Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
Question
Friday, April 20, 2018 5:15 PM
I am using the [CallerMemberName], [CallerFilePath], and [CallerLineNumber] method attributes for a compact way to trace the path of execution, however, when the calling method is a constructor, all I get for CallerMemberName is ".ctor"—without the name of the class the constructor is for. Does anyone know how to display the name of the constructor's class?
I'm using VS Community 2017 v15.6.1 with .NET v4.7.1. (I don't see a C# compiler version number or the version of C# it implements.)
All replies (1)
Monday, April 23, 2018 2:55 PM ✅Answered | 1 vote
CallerMemberName doesn't return the type name for any member, not just constructors. To get the type information you have to pass it as well. Here's how I have my extension method defined.
public static class LoggerExtensions
{
public static void LogCall ( this ILogger source, object instance, object argument, [CallerMemberName] string memberName = "" )
=> LogCall(source, instance, argument?.ToString(), memberName);
public static void LogCall ( this ILogger source, object instance, string arguments, [CallerMemberName] string memberName = "" )
=> source.Debug($"{instance.GetType().Name}.{memberName}({arguments})");
ILogger is our logging infrastructure. You can use whatever you want. Here's how we use it.
public class SomeClass
{
public void Foo ( int arg1, string arg2 )
{
//Outputs SomeClass.Foo(arg1, arg2)
Logger.LogCall(this, $"{arg1}, {arg2}");
}
}
You could get fancy with the arguments if you wanted but with the default member on the end it gets a little complicated.
Michael Taylor http://www.michaeltaylorp3.net