Click here to Skip to main content
15,885,985 members
Articles / Desktop Programming / Windows Forms

A Tiny Expression Evaluator

Rate me:
Please Sign up or sign in to vote.
4.96/5 (71 votes)
18 Aug 2011CPOL10 min read 148.6K   4.1K   124  
A utility that allows you to enter simple and more complex mathematical formulas which will be evaluated and calculated on the spot
using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TinyExe;

namespace TinyExe.Tests
{
    /// <summary>
    /// Summary description for BinaryTests
    /// Tests all && and || operations
    /// </summary>
    [TestClass]
    public class BinaryTests
    {

        [TestMethod]
        public void TestAndTrue()
        {
            bool answer = Expression.Eval<bool>("5 > 4.3 && true");
            Assert.AreEqual(answer, 5 > 4.3 && true);
        }

        [TestMethod]
        public void TestAndOrFalse()
        {
            bool answer = Expression.Eval<bool>("5 < 4.3 && true || \"test\" != \"test\"");
            Assert.AreEqual(answer, 5 < 4.3 && true || "test" != "test");
        }

        [TestMethod]
        public void TestEqStringAndTrue()
        {
            bool answer = Expression.Eval<bool>("\"test\" = \"test\" && true");
            Assert.AreEqual(answer, "test" == "test" && true);
        }

        [TestMethod]
        public void TestConditional()
        {
            double answer = Expression.Eval<double>("\"test\" = \"te\" & \"st\" ? 42 : 52");
            Assert.AreEqual(answer, "test" == "test" ? 42 : 52);
        }

        [TestMethod]
        public void TestConditionalFalse()
        {
            double answer = Expression.Eval<double>("false ? 42 : 52");
            Assert.AreEqual(answer, false ? 42 : 52);
        }

    }
}

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.

License

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


Written By
Architect Rubicon
Netherlands Netherlands
Currently Herre Kuijpers is employed at Rubicon. During his career he developed skills with all kinds of technologies, methodologies and programming languages such as c#, ASP.Net, .Net Core, VC++, Javascript, SQL, Agile, Scrum, DevOps, ALM. Currently he fulfills the role of software architect in various projects.

Herre Kuijpers is a very experienced software architect with deep knowledge of software design and development on the Microsoft .Net platform. He has a broad knowledge of Microsoft products and knows how these, in combination with custom software, can be optimally implemented in the often complex environment of the customer.

Comments and Discussions