I want to start a method whose name is in a string. My server program will be receiving commands from the client, perform those commands, and send the information back to the client. So instead of using a switch with many cases that only execute a method, I thought it would be easier just to send the method name from the client and the server run that method. Google turned up sections of the code below, but it does not work.

Here's what I want to happen.

string MethodName = Receive(); //Gets a string from client, this case it's "Help"
            try
            {
                Commands.Execute(MethodName);
            }

            catch
            {
                Log("No method with the name '" + MethodName + "' exists.");
            }

Here is my Commands class. The Execute code is what I picked up from Google. info always turns up being null, and I don't understand this code anyway so I'm not sure what to do. Is this even the right way to do it?

public static class Commands
    {
        public static void Execute(string CommandName)
        {
            Random rand = new Random();

            System.Reflection.MethodInfo info = rand.GetType().GetMethod(CommandName);
            double r = (double)info.Invoke(rand, null);
        }

        public static void Help()
        {
            Server.Send("BLAH"); //Client will recieve "BLAH" and display it on screen
        }
        // further list of commands

    }

Perfect! :) Works exactly like I wanted it to.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.