I want to convert string to operator in c#
**string type = "+";
int d = 22;
int c = 33;
int total;
total = d + type + c;**
How to do that ?
Regards,
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
You cannot convert a string to an “operator”. An operator is defined for its operands and it doesn’t really make sense to convert a string to an operator if you don’t know what your operands are.
Supposing you do know what operands you have, the problem is no longer one of “conversion” per se but actually you are trying to build a parsing engine. This is a problem of considerable difficulty. Unless you actually are trying to create your own scripting language or something of this nature, it is probably just easier to use a lookup table, with each element in the table referring to some method that can be run on the operands.
In C# it is possible to implement such a data structure using a simple
switchstatement (of course you can make this as fancy as you want ad infinitum but this is the simplest solution).Then you would define suitable methods such as
plusOperatorandminusOperatorto actually implement the logic of your program.This solution is reasonably dirty in that you are hard-coding certain behaviour but really if you want much more than this in terms of good system architecture it becomes a parsing problem. Should you go down this path the Gang of Four design patterns will make for good reference material (particularly patterns such as the Interpreter, Iterator and Composite)