Using and Calling method name

Hi,

Is this possible to call method name dynamically

here is some code to explain that.

string modulename;
string methodname;

modulename = "Mod1";
methodname = getMethodName(modulename);

myClass myobj = new myClass();

myobj.methodname();


I don't know my method name till I call the method. Method name can have paramters but that I can get from tables. So I need to call method which I can get at run time not compile time. How is it possible

Thanks,


Answer this question

Using and Calling method name

  • Sallu

    Just a note: Keep in mind that Reflection comes with a performance overhead.

    Regards,
    Vikram

  • Kila

    You might just want to use delegates, of maybe use an event.

    With an event you can register a method of a certain class with some object that might create or pass an event.

  • Dik

    Yes using Reflection you can.

    Try the following:


    using System;
    using System.Reflection;

    namespace WindowsApplication1
    {
        static class Program
        {
            [STAThread]
            static void Main()
            {
                MyObject obj = new MyObject();

                MethodInfo method = typeof(MyObject).GetMethod("MyMethod");

                method.Invoke(obj, null);

            }

            public class MyObject
            {
                public void MyMethod()
                {
                    Console.WriteLine("MyMethod");
                }
            }
        }
    }


     






  • Using and Calling method name