Click here to Skip to main content
15,886,693 members
Articles / Web Development / ASP.NET

C#-like Expression Evaluator and Type Converter

Rate me:
Please Sign up or sign in to vote.
5.00/5 (13 votes)
22 Apr 2010CPOL10 min read 60.3K   1.6K   39  
Convert types, parse and evaluate expressions in runtime, in .NET 2.0
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using XSharper.Core;

namespace EvalExpression
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            variableBindingSource.Add(new Variable { Name = "Hello", Value = "World" });
            variableBindingSource.Add(new Variable { Name = "A", Value = "50" });
            variableBindingSource.Add(new Variable { Name = "B", Value = "0x0a" });
            variableBindingSource.Add(new Variable { Name = "D", Value = "30.5d" });

            tbExpression.Text = "Math.Sqrt( $A+$B+$hello.Length)+$D+System.IO.Directory.GetFiles('c:\').Length;";
        }

        private void btnCalc_Click(object sender, EventArgs e)
        {
            BasicEvaluationContext be=new BasicEvaluationContext();

            foreach (Variable var in variableBindingSource    )
            {
                ParsingReader pr=new ParsingReader(var.Value);
                be.SetVariable(var.Name, (object)pr.ReadNumber() ?? var.Value);
            }


            try
            {
                tbResult.Text = Dump.ToDump(be.Eval(tbExpression.Text));
            }
            catch (Exception ex)
            {
                tbResult.Text = ex.ToString();
            }

        }


        

    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer http://xsharper.com
Canada Canada
Putting code between curly braces for centuries. Lately, between curly and angle braces too, on http://xsharper.com .

Comments and Discussions