2

Let's say I have a object, with a .Start() method. I want to call the method by typing in the console, like this "object.Start()", that should call the .Start() method.

2
  • 1
    What is the question? Commented Jul 14, 2016 at 18:44
  • He's asking how to call the method on an object that he typed into the console. So if I type "object.Run()" it will call the Run method on his object. Commented Jul 14, 2016 at 18:47

1 Answer 1

4
class Program
{
    static void Main(string[] args)
    {
        var obj = new object(); // Replace here with your object 

        // Parse the method name to call
        var command = Console.ReadLine();
        var methodName = command.Substring(command.LastIndexOf('.')+1).Replace("(", "").Replace(")", "");

        // Use reflection to get the Method
        var type = obj.GetType();
        var methodInfo = type.GetMethod(methodName);

        // Invoke the method here
        methodInfo.Invoke(obj, null);
    }
}
Sign up to request clarification or add additional context in comments.

7 Comments

Can I use parameters with it?
Yes, on the methodInfo.Invoke() instead of passing 'null' for the 2nd parameter, you can pass an object array of the method parameters. So if you want to pass "ABC", and 123, you can call it with methodInfo.Invoke(obj, new object[] { "ABC", 123 });
Ah thanks. And obj in " obj.GetType();" is the object that contains the method?
obj should be your object that you want to call the method on, yeah. Instead of "var obj = new object();" you should replace that with your own object, wherever you're getting it from.
@SamuelKlit if its working for you, can you mark it as the answer?
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.