Click here to Skip to main content
11,428,004 members (59,528 online)
Click here to Skip to main content

C# Eval Function

, 21 Jun 2007 CPOL
Rate this:
Please Sign up or sign in to vote.
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

devilplusplus
Web Developer
China China
No Biography provided

Comments and Discussions

 
QuestionBug in Scanner.cs, at line 453 Pin
Member 864646714-Feb-12 8:42
memberMember 864646714-Feb-12 8:42 
QuestionThanks Pin
bildik9-Aug-11 11:58
memberbildik9-Aug-11 11:58 
GeneralMy vote of 5 Pin
ChenNoam4-Oct-10 22:17
memberChenNoam4-Oct-10 22:17 
GeneralGracias! Pin
Member 44952424-Jun-10 7:00
memberMember 44952424-Jun-10 7:00 
Generalthanks! Pin
bpbrainiak4-May-10 5:00
memberbpbrainiak4-May-10 5:00 
GeneralRounding problem Pin
Pauline Cole30-Nov-09 12:20
memberPauline Cole30-Nov-09 12:20 
GeneralCalculation bug with negative numbers Pin
Pauline Cole12-Oct-09 0:51
memberPauline Cole12-Oct-09 0:51 
GeneralRe: Calculation bug with negative numbers Pin
bpbrainiak4-May-10 4:56
memberbpbrainiak4-May-10 4:56 
GeneralNice Pin
KeitaroSan8-Oct-09 8:17
memberKeitaroSan8-Oct-09 8:17 
GeneralDon't use it for work, only for learning stuff Pin
Dannie Juge30-Sep-09 4:25
memberDannie Juge30-Sep-09 4:25 
QuestionParse as decimal values Pin
palswim15-Jun-09 12:35
memberpalswim15-Jun-09 12:35 
AnswerRe: Parse as decimal values Pin
palswim15-Jun-09 12:37
memberpalswim15-Jun-09 12:37 
GeneralLicense Pin
Member 256327611-May-09 4:54
memberMember 256327611-May-09 4:54 
GeneralRe: License Pin
devilplusplus30-May-09 16:30
memberdevilplusplus30-May-09 16:30 
GeneralOne slight correction in the test code Pin
Andrew Kaiser26-Nov-08 3:26
memberAndrew Kaiser26-Nov-08 3:26 
GeneralCalculation Error Pin
pauf15-Nov-08 1:42
memberpauf15-Nov-08 1:42 
QuestionAssign Variables Pin
j_jpg12-Nov-08 1:54
memberj_jpg12-Nov-08 1:54 
GeneralGreat work Pin
ChenNoam5-Nov-08 23:44
memberChenNoam5-Nov-08 23:44 
Generalcan't parse Pin
jameswei1-Oct-08 17:43
memberjameswei1-Oct-08 17:43 
AnswerRe: can't parse Pin
ChenNoam5-Nov-08 23:47
memberChenNoam5-Nov-08 23:47 
Questionis it possible to add variable in runtime ? Pin
naamakat25-May-08 3:15
membernaamakat25-May-08 3:15 
AnswerRe: is it possible to add variable in runtime ? Pin
Member 110949439-Oct-14 4:06
memberMember 110949439-Oct-14 4:06 
GeneralGetting data from a deep object Pin
ftuttle13-May-08 8:05
memberftuttle13-May-08 8:05 
QuestionLicense Pin
Kjell Ahlstrom2-Mar-08 23:10
memberKjell Ahlstrom2-Mar-08 23:10 
GeneralRe: License Pin
devilplusplus8-Apr-08 15:09
memberdevilplusplus8-Apr-08 15:09 
NewsScript.NET Pin
Extrim18-Oct-07 7:09
memberExtrim18-Oct-07 7:09 
General.Net 1 version Pin
shaluka20-Jun-07 6:50
membershaluka20-Jun-07 6:50 
GeneralRe: .Net 1 version Pin
Pedro Maia Costa21-Jun-07 4:09
memberPedro Maia Costa21-Jun-07 4:09 
GeneralRe: .Net 1 version Pin
devilplusplus21-Jun-07 16:12
memberdevilplusplus21-Jun-07 16:12 
GeneralRe: .Net 1 version Pin
shaluka2-Jul-07 2:12
membershaluka2-Jul-07 2:12 
GeneralRe: .Net 1 version Pin
devilplusplus5-Jul-07 17:55
memberdevilplusplus5-Jul-07 17:55 
QuestionRe: .Net 1 version Pin
shaluka6-Jul-07 0:31
membershaluka6-Jul-07 0:31 
QuestionIs this a bug? Pin
shaluka22-May-07 0:01
membershaluka22-May-07 0:01 
AnswerRe: Is this a bug? Pin
devilplusplus30-May-07 17:04
memberdevilplusplus30-May-07 17:04 
QuestionEscape inverted commas [modified] Pin
shaluka9-May-07 0:58
membershaluka9-May-07 0:58 
AnswerRe: Escape inverted commas Pin
devilplusplus30-May-07 17:05
memberdevilplusplus30-May-07 17:05 
GeneralSpelling Pin
Herbert Sauro27-Apr-07 9:23
memberHerbert Sauro27-Apr-07 9:23 
GeneralRe: Spelling Pin
devilplusplus27-Apr-07 14:53
memberdevilplusplus27-Apr-07 14:53 
GeneralRe: Spelling Pin
Herbert Sauro27-Apr-07 15:11
memberHerbert Sauro27-Apr-07 15:11 
GeneralProblem when evaluate a correct expression after evaluate an invalid expression Pin
zuken2126-Apr-07 17:41
memberzuken2126-Apr-07 17:41 
GeneralProblem with strings Pin
Coyotelapa25-Apr-07 7:27
memberCoyotelapa25-Apr-07 7:27 
AnswerRe: Problem with strings Pin
Coyotelapa25-Apr-07 7:33
memberCoyotelapa25-Apr-07 7:33 
GeneralRe: Problem with strings Pin
devilplusplus25-Apr-07 15:33
memberdevilplusplus25-Apr-07 15:33 
GeneralRe: Problem with strings Pin
Coyotelapa26-Apr-07 2:36
memberCoyotelapa26-Apr-07 2:36 
GeneralProblem using boolean operators Pin
shaluka24-Apr-07 2:21
membershaluka24-Apr-07 2:21 
GeneralRe: Problem using boolean operators Pin
devilplusplus24-Apr-07 15:59
memberdevilplusplus24-Apr-07 15:59 
GeneralRe: Problem using boolean operators Pin
shaluka25-Apr-07 3:49
membershaluka25-Apr-07 3:49 
Generalit is really look like nice work Pin
dengere13-Mar-07 7:51
memberdengere13-Mar-07 7:51 
GeneralRe: it is really look like nice work Pin
devilplusplus13-Mar-07 15:23
memberdevilplusplus13-Mar-07 15:23 
Generalnice Pin
Tittle Joseph6-Mar-06 19:40
memberTittle Joseph6-Mar-06 19:40 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.150428.2 | Last Updated 21 Jun 2007
Article Copyright 2006 by devilplusplus
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid