0

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?

Cyzanfar
  • 6,997
  • 9
  • 43
  • 81
MineGame159
  • 25
  • 1
  • 7
  • I don't get the question, are you looking for some kind of reflection? – Peter Bons Jul 21 '17 at 15:56
  • https://msdn.microsoft.com/en-us/library/system.delegate.dynamicinvoke(v=vs.110).aspx – hoodaticus Jul 21 '17 at 16:01
  • @PeterBons It is possible he just wants a new method right? I'm not sure how `Invoke` works, but I think its used in the wrong way here. I think a standard method call would work fine. Right? – Bender Bending Jul 21 '17 at 16:03

1 Answers1

1

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 });
bornfromanegg
  • 2,826
  • 5
  • 24
  • 40
  • Can you write me how I can create object obj? – MineGame159 Jul 21 '17 at 16:48
  • Assuming you're not in a position to do var obj = new YourObject(), I would refer you to this answer: https://stackoverflow.com/questions/752/get-a-new-object-instance-from-a-type – bornfromanegg Jul 21 '17 at 16:57
  • Why the downvote? If there's something wrong with the answer, please can you explain what it is, or correct the answer? – bornfromanegg Jul 21 '17 at 17:00
  • I don't give you downvote. And can I asign var obj = new YourObject(); without creating new one? – MineGame159 Jul 21 '17 at 17:16
  • @MineGame159 I wasn't accusing you of downvoting - I can't tell who has downvoted, but someone has. As far as your last comment is concerned, I'm not sure what you mean. As I say, it's not *entirely* clear what you're trying to do, so it's difficult to give further advice. If you could add some more specifics to your question, that would help. new YourObject() *will* create a new object. Or are you asking if you need to create the class? If so, then yes. – bornfromanegg Jul 21 '17 at 17:21
  • @bornfromanegg stumbled upon this, gave u an upvote to negate the downvote u don't deserve – Jay Kazama Aug 14 '18 at 04:34