Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

C# Eval Function

0.00/5 (No votes)
21 Jun 2007 1  
C# eval function

Introduction

This article is about a C# eval function, how to parse an expression and evaluate it. It supports Boolean, Bitwise, Arithmetic, Unary, Paren, Member (such as object.property), Indexer (such as array[index]) and ConditionalIf(?:), it also supports Variable assign.

You can use it to evaluate one statement in the C# source code.

It does not use runtime compiler.

It does not use JScript.NET.

It does not use DataTable.

Using the Code

Expression Example

Basic

2+3*5
 true||false
 a+b*c
 a.b+c.d
 a.f(1,2)[b]
 "123"[0]
 "123".Length
 (1).ToString()

All functions or properties use Reflection to eval. It has no global function and its syntax is checked at runtime.
If you let Parameter 'string'=typeof(string), then it can do like this:

string.Format("{0}1111",233)

If a parameter is a type, it will call its static function or property.

Advanced

(a>b)?c:d 

Reflection

("To"+"String")()

Sample Use

using System;
using Jyc.Expr;
namespace TestExpr
{
    class Program
    {
        static void Main(string[] args)
        {
            Parser ep = new Parser();
            Evaluater evaluater = new Evaluater();
            ParameterVariableHolder pvh = new ParameterVariableHolder();

            pvh.Parameters["char"] = new Parameter(typeof(char));
            pvh.Parameters["sbyte"] = new Parameter(typeof(sbyte));
            pvh.Parameters["byte"] = new Parameter(typeof(byte));
            pvh.Parameters["short"] = new Parameter(typeof(short));
            pvh.Parameters["ushort"] = new Parameter(typeof(ushort));
            pvh.Parameters["int"] = new Parameter(typeof(int));
            pvh.Parameters["uint"] = new Parameter(typeof(uint));
            pvh.Parameters["long"] = new Parameter(typeof(string));
            pvh.Parameters["ulong"] = new Parameter(typeof(ulong));
            pvh.Parameters["float"] = new Parameter(typeof(float));
            pvh.Parameters["double"] = new Parameter(typeof(double));
            pvh.Parameters["decimal"] = new Parameter(typeof(decimal));
            pvh.Parameters["DateTime"] = new Parameter(typeof(DateTime));
            pvh.Parameters["string"] = new Parameter(typeof(string));

            pvh.Parameters["Guid"] = new Parameter(typeof(Guid));

            pvh.Parameters["Convert"] = new Parameter(typeof(Convert));
            pvh.Parameters["Math"] = new Parameter(typeof(Math));
            pvh.Parameters["Array "] = new Parameter(typeof(Array));
            pvh.Parameters["Random"] = new Parameter(typeof(Random));
            pvh.Parameters["TimeZone"] = new Parameter(typeof(TimeZone));
            pvh.Parameters["AppDomain "] = new Parameter(typeof(AppDomain));

            pvh.Parameters["Console"] = new Parameter(typeof(Console));

            pvh.Parameters["evaluater"] = new Parameter(evaluater);

            evaluater.VariableHolder = pvh;

            while (true)
            {
                System.Console.WriteLine("Input line,press Return to Eval:");
                string line = System.Console.ReadLine().Trim();
                if (string.IsNullOrEmpty(line))
                    break;
                try
                {
                    Tree tree = ep.Parse(line);

                    tree.Print(System.Console.Out);

                    object result = evaluater.Eval(tree);

                    if( result != null )
                        System.Console.WriteLine("Result:{0}", result);
                    else
                        System.Console.WriteLine("Result is null");
                }
                catch (Exception e)
                {
                    System.Console.WriteLine("Exception:" + e.GetType().Name _
                                               +"->"+ e.Message);
                }
            }
        }
    }
}

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here