Evaluating Expressions

You can evaluate sums in the fly using .net DataTables.

This is how you do it (C# 2005).

string sum = "(1+2)/4";
System.Data.DataTable evaluator = new System.Data.DataTable("temp");
double result;
 
result = (double)evaluator.Compute(sum, null);

This can be pretty damn useful. On a recent project we used tokenised strings which were dynamically replaced with values read from a serialized class.

Consider how powerful this can be. e.g. (VB.NET 2003)

Dim evaluator As New DataTable("temp")
Dim sum As String = "([apples]/[pears])*([oranges]*1.175)"
Dim result As Double
 
    sum = sum.Replace("[apples]", 23)
    sum = sum.Replace("[pears]", 1.21)
    sum = sum.Replace("[oranges]", 99)
 
result = evaluator.Compute(sum, Nothing)
Author Paul Hayman

Paul is the COO of kwiboo ltd and has more than 20 years IT consultancy experience. He has consulted for a number of blue chip companies and has been exposed to the folowing sectors: Utilities, Telecommunications, Insurance, Media, Investment Banking, Leisure, Legal, CRM, Pharmaceuticals, Interactive Gaming, Mobile Communications, Online Services.

Paul is the COO and co-founder of kwiboo (http://www.kwiboo.com/) and is also the creator of GeekZilla.

Add Comment

Name
Comment
 

Your comment has been received and will be shown once it passes moderation.