7

I have an object with some methods and I want to call a method using the method name as string only.

object obj;
obj.method();
Amged
  • 670
  • 1
  • 7
  • 19
  • 1
    Know i know what you want to do. But your question is really confusing... Try to edit your question please. – Jo Smo Aug 21 '14 at 20:33

3 Answers3

11

Given a method MethodName with the signature void MethodName(int num), it would be done something like:

   MethodInfo method = obj.GetType().GetMethod("MethodName", 
         BindingFlags.Public|BindingFlags.Instance)
   method.Invoke(obj, 4) // void method

Hope this helps.

x0n
  • 51,312
  • 7
  • 89
  • 111
2

In addition to reflection you may also want to look at dynamic invocation; which is latebound (i.e. at runtime as opposed to compile time) dispatch of method invocations.

dkackman
  • 15,179
  • 13
  • 69
  • 123
0
object obj;
var dyn = (dynamic) obj;
dyn.method();
Simon
  • 33,714
  • 21
  • 133
  • 202
  • 2
    Yes, but the symbol `method` must still appear as a literal in the code. –  Sep 09 '11 at 02:15