1

i'm developing a math/statistical software. I would like that my customer can write something like :

Function1(value)

Then, depending on the name of the function, call my internal software function. This seems a 'parser' right?

At the moment i'm thinking to solve it with a code like this:

    switch(my_parsed_function_string) {
       case "function1":
          result = function1(value);
       case "function2": 
          result = function2(value);
    ...
    ...
    }

Is there a more elegant way ? A way where a string contained the 'function' name can be lunched without extra developer work ?

Thank you in advance

3 Answers 3

2

Yes, there is. It's called IDictionary. More specifically, in your case it will be more like IDictionary<string, Func<double>>. Thus, your code turns into

var functions = new Dictionary<string, Func<double>>();
var act = functions[my_parsed_function_string].Invoke(arg);
Sign up to request clarification or add additional context in comments.

Comments

1

You can use the Command Pattern. For example:

interface ICommand
{
    void Execute();    
}

class Function1Command : ICommand
{
    public void Execute()
    {
        // ...
    }
}

class Function2Command : ICommand
{
    public void Execute()
    {
        // ...
    }
}

// Bind commands
IDictionary<string, ICommand> commands = new Dictionary<string, ICommand>();
commands["Function1"] = new Function1Command(); // function 1
commands["Function2"] = new Function2Command(); // function 2
// ...

Then you can call your functions like this:

ICommand command = commands[parsedFunctionName] as ICommand;
if(command != null)
{
    command.Execute();
}

Comments

-2

You could declare all the functions in a single object, then reflect on it to get the method names?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.