1

I have a c# .net 2.0CF application where I would like to get not only the type and value of a parameter passed to the function, but also the variable name.

For example:

void Show<PARAM>(PARAM p)
{
    Debug.WriteLine(string.Format("{0} {1} = {2}", typeof(PARAM).ToString, ???, p.ToString() );
}

bool foo = true;
Show(foo);

would output "bool foo = true";

In C++, I can do this with the ## pre-processor macro.

If this can't be done in 2.0, can it be done in 3.5 or 4.0?

Thanks, PaulH

PaulH
  • 7,759
  • 8
  • 66
  • 143
  • http://stackoverflow.com/questions/755254/getting-the-name-of-the-parameter-passed-into-a-method – grenade Dec 16 '10 at 23:29
  • 2
    neat trick for doing this (i think C# 3.0 would be required): http://stackoverflow.com/questions/869610/c-resolving-a-parameter-name-at-runtime – Jake Dec 17 '10 at 01:06

4 Answers4

1

If I remember correctly, this is not possible with reflection as variable names are not in the assemblies, and p is a variable name.

Femaref
  • 60,705
  • 7
  • 138
  • 176
0
using System.Reflection;


ParameterInfo[] info = MethodInfo.GetCurrentMethod().GetParameters();
System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(false);
System.Diagnostics.StackFrame[] frames = trace.GetFrames();

i guess the value can be retrieved from stack frames.

The Paramter Name can be found from the

ParameterInfo[] info = MethodInfo.GetCurrentMethod().GetParameters();

Amit Bagga
  • 648
  • 3
  • 11
  • StackTrace and StackFrame aren't available in the Compact Framework. – PaulH Dec 17 '10 at 15:06
  • also, this isn't true. `StackFrame` only contains file, line and column and the `MethodBase`. Neither contains the original parameter names. – Femaref Dec 17 '10 at 15:23
0
public void Show(int value)
    {
        ParameterInfo[] info = MethodInfo.GetCurrentMethod().GetParameters();
        Trace.WriteLine(string.Format("{0} {1}={2}", info[0].ParameterType.ToString(), info[0].Name, value.ToString()));
    }

output

System.Int32 value=10

Amit Bagga
  • 648
  • 3
  • 11
0

Try using PostSharp it has the support for Compact Framework.

Amit Bagga
  • 648
  • 3
  • 11