Search code examples
c#reflectioncultureinfo

Setting CultureInfo when using reflection Invoke


I'm working on a type converter that looks for a Parse method on the target type. It is found without a problem and invokes just fine. The problem is when passing specific CultureInfo to the Invoke method, it has no effect.

Demo code:

const BindingFlags flags = BindingFlags.Public | BindingFlags.Static;
var parser = typeof(decimal).GetMethod("Parse", flags, null, new[] { typeof(string) }, null);

var result1 = parser.Invoke(null, flags, null, new[] { "123,456" }, CultureInfo.GetCultureInfo("sv-SE"));
var result2 = parser.Invoke(null, flags, null, new[] { "123,456" }, CultureInfo.GetCultureInfo("en-US"));

Console.WriteLine(result1);
Console.WriteLine(result2);

Results (using Swedish locale):
123,456
123,456

So what's happening is that the Parse method is working, but the CultureInfo I pass to Invoke is ignored. The Swedish invocation should be recognising the comma as a decimal, and the American invocation should be recognising the comma as a thousands separator.

What is the CultureInfo parameter of Invoke suppose to be doing? MSDN says

An instance of CultureInfo used to govern the coercion of types. If this is null, the CultureInfo for the current thread is used. (This is necessary to convert a String that represents 1000 to a Double value, for example, since 1000 is represented differently by different cultures.)

Does this have to do with internal conversion when passing parameters to the method you're invoking rather than manipulating the CurrentCulture during invocation? I'm just trying to figure this out before I press on here. I may need to find Parse methods that contain a CultureInfo parameter...at which point I will abandon this idea.


Solution

  • Your assumption is correct; the CultureInfo is only used within Invoke, to convert parameters.

    You need to pass the CultureInfo to the method itself, not to Invoke.