Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combining CallerMemberName with params

Right now (C# 4.0), our logging method looks like

public void Log(string methodName, string messageFormat, params object[] messageParameters)

where the logger does the string formatting, so that the caller does not have to put String.Format's to create a nice log message (and allows for the logger to skip the string formatting if no logviewer is attached).

With C# 5.0, I would like to get rid of the methodName parameter by using the new CallerMemberName attribute but I don't see how this can be combined with the 'params' keyword. Is there a way to do this?

like image 793
Emile Avatar asked Jan 16 '13 09:01

Emile


2 Answers

You could do something like this:

protected static object[] Args(params object[] args)
{
    return args;
}

protected void Log(string message, object[] args = null, [CallerMemberName] string method = "")
{
    // Log
}

To use the log do like this:

Log("My formatted message a1 = {0}, a2 = {2}", Args(10, "Nice"));
like image 94
guilhermekmelo Avatar answered Nov 12 '22 06:11

guilhermekmelo


I believe you simply can't combine params and optional parameters, which are required for CallerMemberName. The best you can do is to use actual array instead of params.

like image 21
svick Avatar answered Nov 12 '22 06:11

svick