Tarek Saied
Tarek Saied

Reputation: 6626

How can I execute a Method when I have its name as a string

Today in an interview (junior web developer) the interviewer asked me this question:

How you can execute a Method when you have its name as a string ( in javascript and in C# )

I can not answer :(

Now when I searched I found this question How to execute a JavaScript function when I have its name as a string

but how do this in c# ??

Upvotes: 1

Views: 1001

Answers (3)

Pranay Rana
Pranay Rana

Reputation: 176956

If you just have name of the method than you can make use of .net Relfection only to run that method..

Check : MethodBase.Invoke Method (Object, Object[])

or

Example :

class Class1
   {
    public int AddNumb(int numb1, int numb2)
    {
      int ans = numb1 + numb2;
      return ans;
    }

  [STAThread]
  static void Main(string[] args)
  {
     Type type1 = typeof(Class1); 
     //Create an instance of the type
     object obj = Activator.CreateInstance(type1);
     object[] mParam = new object[] {5, 10};
     //invoke AddMethod, passing in two parameters
     int res = (int)type1.InvokeMember("AddNumb", BindingFlags.InvokeMethod,
                                        null, obj, mParam);
     Console.Write("Result: {0} \n", res);
   }
  }

Upvotes: 6

kbvishnu
kbvishnu

Reputation: 15650

Good Article. Read it fully. You can call a method not only from a string, but also from a lot of scenarios.

http://www.codeproject.com/Articles/19911/Dynamically-Invoke-A-Method-Given-Strings-with-Met

How to call a shared function which its name came as a parameter

Upvotes: 2

nivlam
nivlam

Reputation: 3253

Assuming that you have the type, you may use reflection to invoke a method by its name.

class Program
{
    static void Main()
    {
        var car = new Car();
        typeof (Car).GetMethod("Drive").Invoke(car, null);
    }
}

public class Car
{
    public void Drive()
    {
        Console.WriteLine("Got here. Drive");
    }
}

If the method you're invoking contains parameters, you may pass the arguments as an object array to Invoke in the same order as the method signature:

var car = new Car();
typeof (Car).GetMethod("Drive").Invoke(car, new object[] { "hello", "world "});

Upvotes: 2

Related Questions