Click to See Complete Forum and Search --> : Call method with variable string


Cuelight
March 17th, 2008, 04:48 AM
hello

I want to call a methode from another class, but with a variable name so I can use the same code and call the methode I want .


//call other class
createProperty x = new createProperty();
//create an array wich will be filled from a method from another class
string[] a = new string[4];
//call the method "Methode"
a = x.Methode();


In the class "createProperty" i have a lot of data in arrays.
So now i want to put a methodename in a string variabele "methodeName" so i can use the code above to call all the methodes;
For example:


string methodeName;
methodeName = "here some code"
//call other class
createProperty x = new createProperty();
//create an array wich will be filled from a method from another class
string[] a = new string[4];
//call the method "Methode"
a = x.MethodeName;


How to do this? Is it possible?

Thx!

boudino
March 17th, 2008, 06:24 AM
Yes, it is possible via reflection:
PropertyInfo pi = x.GetType().GetProperty(methodeName );
object o = pi.GetValue(x); // don't forget to cast to proper type.

Note: check you naming convetions, class names should begin with uppercase.

nelo
March 17th, 2008, 07:29 AM
You can also get the same result through delegates.

public delegate string[] GetDataMethod();
public class Server
{
public string[] GetData1()
{
// add specific code here

}
public string[] GetData2()
{
// add specific code here
}
}

public class Client
{
Server server = new Server();

private void GetData(GetDataMethod dataMethod)
{
string[] data1 = dataMethod;
}
static void Main()
{
GetData(server.GetData1);
GetData(server.GetData2);
}
}

My example is a bit contrived but may show you a different way of doing it.