Question

It seems that for some reason property.GetValue ignores CultureInfo. Here is what I try to achieve:

public static IEnumerable<string> GetViewModelProperties(this IDocumentViewModel vm) {
     foreach (var property in vm.GetType().GetProperties().Where(p => (p.PropertyType.IsPrimitive ||
                                                                 p.PropertyType.GetInterfaces().Any(t => t.IsGenericType && t.GetGenericTypeDefinition() == typeof(IEnumerable<>))) &&
                                                                  p.GetIndexParameters().Count() == 0))
     {
        yield return property.Name + ":" + property.GetValue(vm, System.Reflection.BindingFlags.GetProperty, null, null, System.Globalization.CultureInfo.InvariantCulture);
     }
}

which I simply save to disk using

System.IO.File.WriteAllText("filename.txt", settings.ToString());

and in the resulting file, for property Frequency of type double with value 50.33 I got

Frequency:50,33

which is CurrentCulture (Polish uses coma as separator), but not

Frequency:50.33

as I'd expect. Any ideas what might be wrong?

Was it helpful?

Solution

The GetValue function of PropertyInfo returns an object, not a string - and here's the misconception in your code. That object gets converted to a string because of the + operator with the first argument there being a string (property.Name), but the CultureInfo is not applied to that string conversion.

The solution is to explicitly use the Convert.ToString(object, IFormatProvider) function, i.e.

yield return property.Name + ":" + Convert.ToString(property.GetValue(vm, System.Reflection.BindingFlags.GetProperty, null, null, System.Globalization.CultureInfo.InvariantCulture), System.Globalization.CultureInfo.InvariantCulture);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top