0

So I'm trying to parse a simple arithmetic dynamic expression using System.Linq.Dynamic. This runs fine when executed in an English environment where the CurrentCulture is English-US (and the decimal separator is a plain "." dot). Trying to run the code in a non English environment (e.g. Windows7x64 in Bulgarian, where the decimal separator is a "," comma), ParseLambda fails.

If I put "1.0" in my expression, ParseLambda fails in the Bulgarian environment with a PraseExpression, saying "Invalid real literal '1.0'" (but does not fail in the English environment). If I try to put "1,0" in my expression, ParseLambda fails with a ParseExpression saying "Syntax error" (this one fails in both environments).

Anyone knows a way around this?
Or am I missing something?
Or can I somehow set the culture of the parsed expression?
I need my app to run well on both environments..
My code is running on .NET v4.0 and I have System.Linq.Dynamic.dll (1.0.0.0) added as reference to the project.
Here's the code:

using System;
using System.Linq;
using System.Linq.Dynamic;

namespace DynamicExpressionTest
{
    class Program
    {
        static void Main(string[] args)
        {
            //FAIL: ParseException: Invalid real literal '1.0' (fails only in non-English environment)
            var expression1 = DynamicExpression.ParseLambda(
                new System.Linq.Expressions.ParameterExpression[] { },
                typeof(double), 
                "1.0 + 1.0");
            var result1 = expression1.Compile().DynamicInvoke();
            double resultD1 = System.Convert.ToDouble(result1);
            Console.WriteLine(resultD1);

            //FAIL: ParseException: Syntax error (fails both in English and non-English environments)
            var expression2 = DynamicExpression.ParseLambda(
                new System.Linq.Expressions.ParameterExpression[] { }, 
                typeof(double), 
                "1,0 + 1,0");
            var result2 = expression2.Compile().DynamicInvoke();
            double resultD2 = System.Convert.ToDouble(result2);
            Console.WriteLine(resultD2);
        }
    }
}

Thanks!

alrotem
  • 92
  • 1
  • 7

1 Answers1

2

You can set the current culture before running that code. E.g. add this line before your code that only works with an English-style decimal separator:

System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
Clafou
  • 15,250
  • 7
  • 58
  • 89
  • Yes, it seems to have done the trick. I was afraid it could have meddled with my app's culture, but I'm setting it on the CurrentUICulture so it seems the CurrentCulture is safe to change (and behind the scenes the data is always in InvariantCulture). Thanks @Clafou! – alrotem Dec 07 '12 at 16:26