3

Possible Duplicate:
Is there a string math evaluator in .NET?

Is there a way to convert the operator code without doing a check for "+", "-", "*", "/" and then passing the value?

using System;

namespace ConsoleApplication1
{
    class Program
    {
        private static void Main(string[] args)
        {
            string operator = "+";
            int inputOne = 2;
            int inputTwo = 5;

            Console.WriteLine(Result(inputOne, inputTwo, operator));
            Console.ReadLine();
        }


        public static string Result(int one, int two, string computeOperator)
        {
            if (computeOperator == "+")
            {
                return (one + two).ToString();
            }

            if (computeOperator == "-")
            {
                return (one - two).ToString();
            }

            //and so on...

            return "0";
        }
    }
}
Community
  • 1
  • 1
Ray Clark
  • 141
  • 1
  • 1
  • 8

3 Answers3

6

No, not the way you appear to be wanting to. A string literal, by definition, cannot be converted into an operator.

Zaid Masud
  • 13,225
  • 9
  • 67
  • 88
  • I don't know about that. There are several possible approaches in the link that @Dan Andrews posted above. – David Dec 20 '12 at 15:41
  • @DavidStratton under the hood, those possible approaches are doing a string comparison similar to the way the OP is doing. They wouldn't be converting a string literal to an operator. – Zaid Masud Dec 20 '12 at 16:00
  • You're right. I guess I was just looking at the end result - "can he achieve what he wanted (taking a string that is clearly a mathematicval expresssion and calculating it) by taking a different approach", not "can he achieve what he wants using the approach he is specifically asking about". But you are right in pointing out that the approach he was asking about will not work. Sometimes I focus so much on the end result I forget to pay attention on how to get there. Something I need to improve upon at times. I bet I'd be a better coder if I did pay more attention to how I get there. ;-) – David Dec 20 '12 at 16:06
1

Your question is similar to example sample of lexical analyzer in c#. You can try to use one of those lexical analyzers but unless you're going to be parsing a lot of text, it might not be worth it.

For reference, this is probably the most relevant of the link from that answer...

Lucene Text Analyzer - C# | CodeProject

Community
  • 1
  • 1
Jeff
  • 13,943
  • 11
  • 55
  • 103
0

Simply NO. But you can do calculation using Eval

GajendraSinghParihar
  • 9,051
  • 11
  • 36
  • 64