Passing Array using Reflection

G

Guest

Hi ,
Can anybody help me why this code is failing?
I am passing an array using reflection.

using System;
using System.Reflection;
using System.Collections;

namespace ReflectionTest
{
public class M
{
public void Method(string[] x)
{
Console.WriteLine(x[0]);
//x ="Changed value";

}
[STAThread]
public static void Main()
{
Hashtable h = new Hashtable();
h.Add("ABC", "Initial value"); //Set initial value
h.Add("BCD", "Second value"); //Set second value
Type t = typeof(M);
M m = (M)Activator.CreateInstance(t);//Create instance of M
Type [] p = new Type[2];

p[0] = Type.GetType("System.String");//typeof(ref string)
p[1] = Type.GetType("System.String");//typeof(ref string)
MethodInfo mi = t.GetMethod("Method", p);//Get the method
Object [] ps = {h["ABC"],h["BCD"]}; //Create param array
mi.Invoke(m,ps);
Console.WriteLine(h["ABC"]); //**output is "Initial value"
Console.WriteLine(ps[0].ToString());

}

}
}

Thanks in advance.

- Vignesh
 
E

Erick Sgarbi

Considering that your method is taking an array of Strings...
public void Method(string[] x)

The method signature is not 2 strings but rather an array of strings:
Type [] p = new Type[];
p[0] = Type.GetType("System.String[]");

Next you are passing an array of objects from the Hashtable indexer
instead of an array of string as well as are not passing the appropriate
argument... you must pass an array of objects relating to the signature
which is an array of strings (string[]):
Object [] ps = {h["ABC"],h["BCD"]};

It should be:
System.Object [] ps = new System.Object[]
{
new System.String[]
{
h["ABC"].ToString(),
h["BCD"].ToString()
}
};


HTH
Erick Sgarbi
www.blog.csharpbox.com



Hi ,
Can anybody help me why this code is failing?
I am passing an array using reflection.

using System;
using System.Reflection;
using System.Collections;

namespace ReflectionTest
{
public class M
{
public void Method(string[] x)
{
Console.WriteLine(x[0]);
//x ="Changed value";

}
[STAThread]
public static void Main()
{
Hashtable h = new Hashtable();
h.Add("ABC", "Initial value"); //Set initial value
h.Add("BCD", "Second value"); //Set second value
Type t = typeof(M);
M m = (M)Activator.CreateInstance(t);//Create instance of M
Type [] p = new Type[2];

p[0] = Type.GetType("System.String");//typeof(ref string)
p[1] = Type.GetType("System.String");//typeof(ref string)
MethodInfo mi = t.GetMethod("Method", p);//Get the method
Object [] ps = {h["ABC"],h["BCD"]}; //Create param array
mi.Invoke(m,ps);
Console.WriteLine(h["ABC"]); //**output is "Initial value"
Console.WriteLine(ps[0].ToString());

}

}
}

Thanks in advance.

- Vignesh
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top