Cinchoo – String.Evaluate(), Extension Method

In this section, I’ll talk about Evaluate extension method. This method used to evaluate a mathematical expression string and returns final output as object. Please see the below samples on how to use it.

1. Add reference to Cinchoo.Core.dll assembly

2. Namespace System

Sample:

static void Main(string[] args)
{
    //Numeric expression
    Console.WriteLine("Output of {{100 + 20}}: " + "{100 + 20}}".Evaluate());
    Console.WriteLine("Output of {{100 + 20 * 2 + 10}}: " + "{100 + 20 * 2 + 10}}".Evaluate());
    Console.WriteLine("Output of {{100 + 20 * (2 + 10)}}: " + "{100 + 20 * (2 + 10)}}".Evaluate());
    Console.WriteLine("Output of {{100.05 + 10.05}}: " + "{100.05 + 10.05}}".Evaluate());
    Console.WriteLine();

    //String expression
    Console.WriteLine("Output of {'First ' + 'Second'}}: " + "{'First ' + 'Second'}}".Evaluate());
    Console.WriteLine();

    //Expression contains properties
    Console.WriteLine("Output of {'%%APPLICATION_NAME%%'}}: " + "{'%%APPLICATION_NAME%%'}}".Evaluate());
    Console.WriteLine("Output of {'%%NOW%%'}}: " + "{'%%NOW%%'}}".Evaluate());
    Console.WriteLine("Output of {'%%TODAY%%'}}: " + "{'%%TODAY%%'}}".Evaluate());
    Console.WriteLine();
}

When you run the above code, the output will be

Output of {{100 + 20}}: 120
Output of {{100 + 20 * 2 + 10}}: 150
Output of {{100 + 20 * (2 + 10)}}: 340
Output of {{100.05 + 10.05}}: 110.1

Output of {{'First ' + 'Second'}}: First Second

Output of {{'%%APPLICATION_NAME%%'}}: Cinchoo.Core.ExpressionEvaluator.Test.exe
Output of {{'%%NOW%%'}}: 4:43 PM
Output of {{'%%TODAY%%'}}: 1/11/2012

Press any key to continue . . .

Happy coding!!!

PS: Please refer Property Replacer section for information about available properties and defining custom properties.


Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s