MineGame159
MineGame159

Reputation: 25

c# - Invoke method with parameters

How can I invoke a method with parameters?

I have this:

List<String> methods = new List<String>(new List<String>{ "first", "second" });
int number = 4;
String text = "Hi";
bool isTrue = false;

And want to invoke the method like this:

if (isTrue)
    Invoke(methods[0], number);
else if (!isTrue)
    Invoke(methods[1], { number, text });

Is it possible?

Upvotes: 0

Views: 5601

Answers (1)

bornfromanegg
bornfromanegg

Reputation: 2918

I'm not entirely sure what you're asking, but I am assuming that you are trying to call a method by it's name, and that that method has parameters. Assuming also that:

  • You have an object called obj that is of type YourObject
  • YourObject contains public, non-static methods named first and second

then you should be able to use the following:

if (isTrue)
    typeof(YourObject).GetMethod(methods[0]).Invoke(obj, new[] { number });
else if (!isTrue)
    typeof(YourObject).GetMethod(methods[1]).Invoke(obj, new[] { number, text });

Upvotes: 1

Related Questions