views:

153

answers:

2

I need to log all the function parameters in a dozen functions.

Is there a way to pro grammatically determine all the parameters and their values (or at least their .ToString() value)? Perhaps via reflection?

+1  A: 

Here is an example of how to do this with PostSharp

http://consultingblogs.emc.com/merrickchaffer/archive/2009/08/04/using-postsharp-to-log-method-entry-and-exit-in-net-code.aspx

You can also roll your own

http://www.developerfusion.com/article/5307/aspect-oriented-programming-using-net/3/

Bob
Wish I could upvote this twice, since I feel that both current answers give value, but I feel this will provide an actual solution.
Lasse V. Karlsen
+1  A: 

To the best of my knowledge there's no way to use reflection to dynamically list and determine value of local variables. You can use reflection to get type information about the parameters of a method, but only the declared type - you can't automatically get information about the actual arguments, because the reflection metadata gives information about the method definition, not the specific values passed to it at runtime.

You can, however, do something like this:

static class Extensions
{
    public static string GetTypeAndValue(this object obj) 
    { 
        return String.Format("{0}: {1}", obj.GetType().Name, obj.ToString()); 
    }
}

Then, from within each method in which you want to perform logging, do something like

private void SomeMethodToBeLogged(string some_string, int some_int, bool some_bool)
{
    Logger.Log(String.Format("SomeMethodToBeLogged({0}, {1}, {2})", 
        some_string.GetTypeAndValue(), 
        some_int.GetTypeAndValue(), 
        some_bool.GetTypeAndValue()));
}
Dathan
obj.GetType().Name produces the name of the Type, not the name of the variable (which is what I need).
AngryHacker
... and which you can't get, unless you actually write code to do it, that is, record the variable name and its value, or let someone else do it, like the other answer here regarding PostSharp. Reflection looks at metadata, classes, etc. not at actual instances and their current properties (like parameter values, etc.)
Lasse V. Karlsen