Click here to Skip to main content
12,696,493 members (31,087 online)
Click here to Skip to main content

Tagged as


406 bookmarked

A Calculation Engine for .NET

, 1 Sep 2013 CPOL
A calculation engine that is small, fast, and extensible.
using System;
using System.Diagnostics;
using System.Collections.Generic;
using System.Text;

namespace CalcEngine
    static class Logical
        public static void Register(CalcEngine ce)
            ce.RegisterFunction("AND", 1, int.MaxValue, And);
            ce.RegisterFunction("OR", 1, int.MaxValue, Or);
            ce.RegisterFunction("NOT", 1, Not);
            ce.RegisterFunction("IF", 3, If);
            ce.RegisterFunction("TRUE", 0, True);
            ce.RegisterFunction("FALSE", 0, False);
        public static void Test(CalcEngine ce)
            ce.Test("AND(true, true)", true);
            ce.Test("AND(true, false)", false);
            ce.Test("AND(false, true)", false);
            ce.Test("AND(false, false)", false);
            ce.Test("OR(true, true)", true);
            ce.Test("OR(true, false)", true);
            ce.Test("OR(false, true)", true);
            ce.Test("OR(false, false)", false);
            ce.Test("NOT(false)", true);
            ce.Test("NOT(true)", false);
            ce.Test("IF(5 > 4, true, false)", true);
            ce.Test("IF(5 > 14, true, false)", false);
            ce.Test("TRUE()", true);
            ce.Test("FALSE()", false);
        static object And(List<Expression> p)
            var b = true;
            foreach (var v in p)
                b = b && (bool)v;
            return b;
        static object Or(List<Expression> p)
            var b = false;
            foreach (var v in p)
                b = b || (bool)v;
            return b;
        static object Not(List<Expression> p)
            return !(bool)p[0];
        static object If(List<Expression> p)
            return (bool)p[0] 
                ? p[1].Evaluate() 
                : p[2].Evaluate();
        static object True(List<Expression> p)
            return true;
        static object False(List<Expression> p)
            return false;

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.


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


About the Author

Bernardo Castilho
Chief Technology Officer ComponentOne
United States United States
No Biography provided

You may also be interested in...

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.170118.1 | Last Updated 1 Sep 2013
Article Copyright 2011 by Bernardo Castilho
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid