2

Is it possible to convert a lambda expression like x => x + 1.5 to string using specific culture/format options? I know I can do:

Expression<Func<double,double>> expr = x => x + 1.5;
string s = expr.Body.ToString();

But with some app language settings it gives s equal to "x + 1,5" (with a comma instead of a dot). It seems that ToString() takes current culture info.

How to get back the string in its original form, culture-invariant?

pbalaga
  • 2,018
  • 1
  • 21
  • 33

1 Answers1

2

There is a way to do it, but it's really ugly... just change the current culture temporarily:

var previousCulture = Thread.CurrentThread.CurrentCulture;
try
{
    Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
    Expression<Func<double,double>> expr = x => x + 1.5;
    string s = expr.Body.ToString();
}
finally
{
    Thread.CurrentThread.CurrentCulture = previousCulture;
}
Thomas Levesque
  • 286,951
  • 70
  • 623
  • 758
  • Any idea why this doesn't work? `string.Format(CultureInfo.GetCultureInfo("en-US"), "{0}", expr.Body)` – Sebastian Piu Dec 13 '11 at 19:39
  • Thanks for the response. May I ask what is the `try` block for in this case? Where do you expect an exception to occur? – pbalaga Dec 13 '11 at 19:43
  • 1
    @rook, actually in this case it's not really useful, but when I temporarily change global state (such as the current culture), I want to make sure I put it back the way it was, should anything happen. A finally block is a good way to ensure that. – Thomas Levesque Dec 13 '11 at 20:36
  • @SebastianPiu, this works only if the formatted type implements IFormattable – Thomas Levesque Dec 13 '11 at 20:38