1

Is it possible to deserialize decimal with invariant culture?

I can do that with this pattern:

 [XmlIgnore]
    public decimal CurrencyValue { get; set; }

    [XmlAttribute("CurrencyValue")]
    public string CurrencyValueString
    {
        set { CurrencyValue = Convert.ToDecimal(value, CultureInfo.InvariantCulture); }
    }

But my container consists of many decimals and I'm embarrassed doing this many times. Moreover it's look strange.

adamo94
  • 507
  • 1
  • 6
  • 15

2 Answers2

0

You could decide to use the InvariantCulture as a default for the current thread, or for the whole application, using CultureInfo.DefaultThreadCurrentCulture, if you're on .Net 4.5.

See here for informations.

Community
  • 1
  • 1
Alberto Chiesa
  • 7,022
  • 2
  • 26
  • 53
-1

I made a test

XmlSerializer ser = new XmlSerializer(typeof(decimal));
        StringBuilder builder = new StringBuilder();
        CultureInfo.DefaultThreadCurrentCulture = CultureInfo.InvariantCulture;
        var row = XElement.Parse(@"<decimal>321,64</decimal>");
        using (var xmlReader = row.CreateReader())
        {
           var result = (decimal)ser.Deserialize(xmlReader);
        }

Unfortunetely this throws exception but the second example returns 32164(BTW. is it good result? )

XmlSerializer ser = new XmlSerializer(typeof(string));
        StringBuilder builder = new StringBuilder();
        var row = XElement.Parse(@"<string>321,64</string>");
        using (var xmlReader = row.CreateReader())
        {
           var result = (string)ser.Deserialize(xmlReader);
           decimal s = Convert.ToDecimal(result,CultureInfo.InvariantCulture);
        }
adamo94
  • 507
  • 1
  • 6
  • 15