Click here to Skip to main content
15,885,141 members
Articles / Programming Languages / C#
Article

C# Eval Function

Rate me:
Please Sign up or sign in to vote.
3.58/5 (20 votes)
21 Jun 2007CPOL 263.2K   3.4K   49   50
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:

C#
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

C#
("To"+"String")()

Sample Use

C#
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
China China
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralRe: .Net 1 version Pin
Pedro Maia Costa21-Jun-07 3:09
Pedro Maia Costa21-Jun-07 3:09 
GeneralRe: .Net 1 version Pin
devilplusplus21-Jun-07 15:12
devilplusplus21-Jun-07 15:12 
GeneralRe: .Net 1 version Pin
shaluka2-Jul-07 1:12
shaluka2-Jul-07 1:12 
GeneralRe: .Net 1 version Pin
devilplusplus5-Jul-07 16:55
devilplusplus5-Jul-07 16:55 
QuestionRe: .Net 1 version Pin
shaluka5-Jul-07 23:31
shaluka5-Jul-07 23:31 
QuestionIs this a bug? Pin
shaluka21-May-07 23:01
shaluka21-May-07 23:01 
AnswerRe: Is this a bug? Pin
devilplusplus30-May-07 16:04
devilplusplus30-May-07 16:04 
QuestionEscape inverted commas [modified] Pin
shaluka8-May-07 23:58
shaluka8-May-07 23:58 
Hi, how can I escape inverted commas (") ?

One more question.

How come if I do the following results look wrong:

1 < 2
true

1 > 2
true

Thanks
Sha


-- modified at 7:49 Wednesday 9th May, 2007
AnswerRe: Escape inverted commas Pin
devilplusplus30-May-07 16:05
devilplusplus30-May-07 16:05 
GeneralSpelling Pin
Herbert Sauro27-Apr-07 8:23
Herbert Sauro27-Apr-07 8:23 
GeneralRe: Spelling Pin
devilplusplus27-Apr-07 13:53
devilplusplus27-Apr-07 13:53 
GeneralRe: Spelling Pin
Herbert Sauro27-Apr-07 14:11
Herbert Sauro27-Apr-07 14:11 
GeneralProblem when evaluate a correct expression after evaluate an invalid expression Pin
zuken2126-Apr-07 16:41
zuken2126-Apr-07 16:41 
GeneralProblem with strings Pin
Aleksandar Lalic25-Apr-07 6:27
Aleksandar Lalic25-Apr-07 6:27 
AnswerRe: Problem with strings Pin
Aleksandar Lalic25-Apr-07 6:33
Aleksandar Lalic25-Apr-07 6:33 
GeneralRe: Problem with strings Pin
devilplusplus25-Apr-07 14:33
devilplusplus25-Apr-07 14:33 
GeneralRe: Problem with strings Pin
Aleksandar Lalic26-Apr-07 1:36
Aleksandar Lalic26-Apr-07 1:36 
GeneralProblem using boolean operators Pin
shaluka24-Apr-07 1:21
shaluka24-Apr-07 1:21 
GeneralRe: Problem using boolean operators Pin
devilplusplus24-Apr-07 14:59
devilplusplus24-Apr-07 14:59 
GeneralRe: Problem using boolean operators Pin
shaluka25-Apr-07 2:49
shaluka25-Apr-07 2:49 
Generalit is really look like nice work Pin
Nuri YILMAZ13-Mar-07 6:51
Nuri YILMAZ13-Mar-07 6:51 
GeneralRe: it is really look like nice work Pin
devilplusplus13-Mar-07 14:23
devilplusplus13-Mar-07 14:23 
Generalnice Pin
Tittle Joseph6-Mar-06 18:40
Tittle Joseph6-Mar-06 18:40 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.