1

I would like to create a textbox in a windows form using C# .Net, that will be able to handle simple calculations. For example, if the user writes in the textbox =5*7 then when the textbox gets validated the textbox.Text = 35.

My question is how can I convert the string "=5*7" to doubles and symbols so as to make the calculations.

チーズパン
  • 2,752
  • 8
  • 42
  • 63
Charitini
  • 33
  • 8

2 Answers2

2

use the CodeAnalysis.CSharp.Scripting library here how to use it wiki

0

You can use CodeAnalysis.CSharp.Scripting library for this. It is available from Nuget

using Microsoft.CodeAnalysis.CSharp.Scripting;
using System;

namespace ExpressionParser
{
    class Program
    {
        static void Main(string[] args)
        {
            //Demonstrate evaluating C# code
            var result = CSharpScript.EvaluateAsync("System.DateTime.Now.AddDays(-1) > System.DateTime.Now").Result;
            Console.WriteLine(result.ToString());

            //Demonstrate evaluating simple expressions
            var result2 = CSharpScript.EvaluateAsync(" 5 * 7").Result;
            Console.WriteLine(result2);
            Console.ReadKey();
        }
    }
}

nuget packages:

<package id="Microsoft.CodeAnalysis.Analyzers" version="1.1.0" targetFramework="net461" /> <package id="Microsoft.CodeAnalysis.Common" version="1.1.1" targetFramework="net461" /> <package id="Microsoft.CodeAnalysis.CSharp" version="1.1.1" targetFramework="net461" /> <package id="Microsoft.CodeAnalysis.CSharp.Scripting" version="1.1.1" targetFramework="net461" /> <package id="Microsoft.CodeAnalysis.Scripting" version="1.1.1" targetFramework="net461" /> <package id="Microsoft.CodeAnalysis.Scripting.Common" version="1.1.1" targetFramework="net461" />

Crowcoder
  • 11,250
  • 3
  • 36
  • 45
  • I tried including the nuget package `Microsoft.CodeAnalysis.CSharp.Scripting 1.1.1`, but that does not include the namespace `Microsoft.CodeAnalysis.CSharp.Scripting` - so the example won't compile on my machine. As it seems, `CSharpScript` does not exist. Could you shed a light on this please? – Matt Mar 22 '16 at 13:06
  • @Matt see edit for the Nuget packages – Crowcoder Mar 22 '16 at 13:27
  • You are right, thank you, I added the package to an empty console project and inserted your code. The key is to change the framework version to 4.6.1 before adding the nuget package - In my case the default setting for the framework was 4.5.2, which did not work (it was trying to import something but failed). After that change, it worked instantly. – Matt Mar 22 '16 at 14:03