Landin Martens
Landin Martens

Reputation: 3333

Get parameter values from method at run time

I have the current method example:

public void MethodName(string param1,int param2)
{
    object[] obj = new object[] { (object) param1, (object) param2 };
    //Code to that uses this array to invoke dynamic methods
}

Is there a dynamic way (I am guessing using reflection) that will get the current executing method parameter values and place them in a object array? I have read that you can get parameter information using MethodBase and MethodInfo but those only have information about the parameter and not the value it self which is what I need.

So for example if I pass "test" and 1 as method parameters without coding for the specific parameters can I get a object array with two indexes { "test", 1 }?

I would really like to not have to use a third party API, but if it has source code for that API then I will accept that as an answer as long as its not a huge API and there is no simple way to do it without this API.

I am sure there must be a way, maybe using the stack, who knows. You guys are the experts and that is why I come here.

Thank you in advance, I can't wait to see how this is done.

EDIT

It may not be clear so here some extra information. This code example is just that, an example to show what I want. It would be to bloated and big to show the actual code where it is needed but the question is how to get the array without manually creating one. I need to some how get the values and place them in a array without coding the specific parameters.

Upvotes: 1

Views: 3716

Answers (1)

YohannP
YohannP

Reputation: 309

Using reflection you can extract the parameters name and metadata but not the actual values :

  class Program
    {
        static void Main(string[] args)
        {
            Program p = new Program();
            p.testMethod("abcd", 1);
            Console.ReadLine();
        }

        public void testMethod(string a, int b)
        {
            System.Diagnostics.StackTrace st = new System.Diagnostics.StackTrace();
            StackFrame sf = st.GetFrame(0);
            ParameterInfo[] pis = sf.GetMethod().GetParameters();

            foreach (ParameterInfo pi in pis)
            {
                Console.Out.WriteLine(pi.Name);
            }
        }
    }

Upvotes: 2

Related Questions