1

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# ??

Community
  • 1
  • 1
Tarek Saied
  • 6,482
  • 20
  • 67
  • 111
  • 10
    This question seems to be trying gather whether you know an important part of C#, Reflection. Maybe instead of trying to find the answer to just this specific question, you should read a book about C#. – Yuriy Faktorovich May 14 '12 at 05:58
  • Probably for c# the better answer would be "You should avoid that. If you need that ever - then you probably do something in a very wrong way" – zerkms May 14 '12 at 06:01
  • The answer is to use Reflection. Look here: http://stackoverflow.com/questions/540066/calling-a-function-from-a-string-in-c-sharp – Leo May 14 '12 at 06:02
  • @zerkms I don't want to start this here, but there are tons of right reasons to use C# reflection. http://stackoverflow.com/questions/1458256/why-use-of-reflection-in-net-c-sharp-code-are-recommended – Yuriy Faktorovich May 14 '12 at 06:05
  • 1
    @Yuriy Faktorovich: I didn't say that there is no reason to use reflection. But I did say that the case when you need to call a method by its name is a **code smell** – zerkms May 14 '12 at 06:07
  • 2
    It might be a duplicate question. I think you can easily found it if you search in Google. Always ask google first, if you don't get the desired result ask stackoverflow. – kbvishnu May 14 '12 at 06:08
  • 2
    Its absolutly a duplicated question: http://stackoverflow.com/questions/540066/calling-a-function-from-a-string-in-c-sharp And there are a lot more infos on google: https://www.google.de/search?ix=acb&sourceid=chrome&ie=UTF-8&q=c%23+execute+method+by+string – Felix K. May 14 '12 at 06:09
  • @zerkms No, you said "then you probably do something in a very wrong way", not a code smell. Also it isn't necessarily even a code smell, and quite possible the best, if not only way. – Yuriy Faktorovich May 14 '12 at 06:30
  • @Yuriy Faktorovich: very wrong === code smell. I don't say there are no valid cases for that, but in 99% cases it is just a result of bad architecture. – zerkms May 14 '12 at 06:50

3 Answers3

6

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);
   }
  }
Pranay Rana
  • 175,020
  • 35
  • 237
  • 263
2

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 "});
nivlam
  • 3,223
  • 4
  • 30
  • 39
2

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

Community
  • 1
  • 1
kbvishnu
  • 14,760
  • 19
  • 71
  • 101
  • negative ? pls mention the reason ? – kbvishnu May 14 '12 at 06:09
  • -1. If you just want to provide links - consder comments instead or propose "close as duplicate" if link on SO for exact question. Otherwise provide summary of the link. – Alexei Levenkov May 14 '12 at 06:10
  • @AlexeiLevenkov this link contains information he required and other probable ways to implement reflection. Any way if I copy the code here , he need to visit the link for more info. So I did like this. I'm sorry for this and thanks for your comment. :) – kbvishnu May 14 '12 at 07:28