Consider this JavaScript code snippet:
Object.prototype.log = function() {
// here, you have a centralized place to do logging stuff;
console.log(this);
}
function fullName(firstName, lastName)
{
// here, using a simple one-line code, you can log all parameters;
arguments.log();
}
fullName('saeed', 'nemati');
Can we have a similar mechanism for logging all the parameters passed into a method, in C#?
Note: What I've done was to use reflection, but with no success:
public static void LogParameters(this ParameterInfo[] parameters)
{
StringBuilder builder = new StringBuilder();
builder.Append("*****************\r\n");
builder.Append("Parameters\r\n");
parameters.ToList().ForEach(pi =>
{
builder.AppendFormat("{0} => {1}\r\n", pi.Name, pi.DefaultValue);
// The problem is that, I can't get the value of the parameter here
});
builder.Append("*****************");
Log.Write(builder.ToString());
}
public string GetFullName(string firstName, string lastName)
{
MethodBase.GetCurrentMethod().GetParameters().LogParameters();
return firstName + " - " + lastName;
}
GetFullName("saeed", "neamati");
No, you can't obtain parameter values using reflection. You'd have to pass them into the logging method explicitly.
You may be able to do this using the debugger API, but you probably don't want to. I would just do it explicitly if I were you - and in fact, that's likely to end up with more useful logging, as you can log only what's important, and give some context in a message as well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With