C# doesn’t have a built-in way of handling symbols at run-time. Not every language out there is LISP 🙂
In the general case, you’re talking about a compiler – something that takes code as input, and produces executable. There’s many ways to invoke the C# compiler in C#, and they’re very easy to find, so I’m not going to go deeper into this – it’s likely a huge overkill, and presents many troubles with security etc. If you go with run-time code generation at all, Expression
s might be a decent compromise between security and flexibility.
In a more specific case, you really want to define your operations the way you want them, which gives you full control over the operations you allow the user (be it a live user or some script, no difference).
Indeed, a simple switch
is the clearest solution for something as simple as this. It doesn’t scale well if you want to expand to a full-blown domain-specific language, but it doesn’t need any special knowledge (e.g. compiler theory) – just do the simplest thing that works.
switch (operator)
{
case '+': return op1 + op2;
case '-': return op1 - op2;
...
}
Don’t make things more complicated than they need to be. Especially when it comes to things like run-time code generation or evaluation 🙂