Click here to Skip to main content
Licence CPOL
First Posted 6 Mar 2006
Views 134,115
Downloads 1,411
Bookmarked 44 times

C# Eval Function

By | 21 Jun 2007 | Article
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)

About the Author

devilplusplus

Web Developer

China China

Member



Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
QuestionBug in Scanner.cs, at line 453 PinmemberMember 86464677:42 14 Feb '12  
QuestionThanks Pinmemberbildik10:58 9 Aug '11  
GeneralMy vote of 5 PinmemberChenNoam21:17 4 Oct '10  
GeneralGracias! PinmemberMember 44952426:00 4 Jun '10  
Generalthanks! Pinmemberbpbrainiak4:00 4 May '10  
GeneralRounding problem PinmemberPauline Cole11:20 30 Nov '09  
GeneralCalculation bug with negative numbers PinmemberPauline Cole23:51 11 Oct '09  
GeneralRe: Calculation bug with negative numbers Pinmemberbpbrainiak3:56 4 May '10  
GeneralNice PinmemberKeitaroSan7:17 8 Oct '09  
GeneralDon't use it for work, only for learning stuff PinmemberDannie Juge3:25 30 Sep '09  
QuestionParse as decimal values Pinmemberpalswim11:35 15 Jun '09  
AnswerRe: Parse as decimal values Pinmemberpalswim11:37 15 Jun '09  
GeneralLicense PinmemberMember 25632763:54 11 May '09  
GeneralRe: License Pinmemberdevilplusplus15:30 30 May '09  
GeneralOne slight correction in the test code PinmemberAndrew Kaiser2:26 26 Nov '08  
GeneralCalculation Error Pinmemberpauf0:42 15 Nov '08  
QuestionAssign Variables Pinmemberj_jpg0:54 12 Nov '08  
GeneralGreat work PinmemberChenNoam22:44 5 Nov '08  
Generalcan't parse Pinmemberjameswei16:43 1 Oct '08  
AnswerRe: can't parse PinmemberChenNoam22:47 5 Nov '08  
Questionis it possible to add variable in runtime ? Pinmembernaamakat2:15 25 May '08  
GeneralGetting data from a deep object Pinmemberftuttle7:05 13 May '08  
QuestionLicense PinmemberKjell Ahlstrom22:10 2 Mar '08  
GeneralRe: License Pinmemberdevilplusplus14:09 8 Apr '08  
NewsScript.NET PinmemberExtrim6:09 18 Oct '07  

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.

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