Passing a method's name as a parameter

private void Method1()
{
    //Do something
    Log("Something","Method1");
}

private void Method2()
{
    //Do something
    Log("Something","Method2");
}

private void Log(string message, string method)
{
    //Write to a log file
    Trace.TraceInformation(message + "happened at " + method);
}

I have several methods like Method1 and Method2 above, and i would like some way pass the method's name as a parameter, without manually editing the code.

Is that possible?

Jon Skeet
people
quotationmark

As of C# 5, this is really easy using caller info attributes:

private void Method1()
{
    //Do something
    Log("Something");
}

private void Method2()
{
    //Do something
    Log("Something");
}

private void Log(string message, [CallerMemberName] string method = null)
{
    //Write to a log file
    Trace.TraceInformation(message + "happened at " + method);
}

In terms of getting this working:

  • You must be using the C# 5 (or later) compiler, otherwise it won't know to handle the attributes specially
  • The attributes have to exist in your target environment. Options there:
    • In .NET 4.5 the attributes are simply present
    • For .NET 4 you can use the Microsoft.Bcl NuGet package
    • For earlier versions of .NET, copy the attribute declaration into your own code, making sure you use the same namespace. When you later move to a new version of .NET, you'll need to remove it again.

people

See more on this question at Stackoverflow