Issue when serializing double or single type Min or Max value


The following code causes an exception when it should not.
    public void TestMinMax()
            var ser = new YAXSerializer(typeof (double), YAXExceptionHandlingPolicies.ThrowErrorsOnly,
                                        YAXExceptionTypes.Warning, YAXSerializationOptions.SerializeNullObjects);
            double d = 0.55;
            var xml = ser.Serialize(d);
            var deseredInstance = ser.Deserialize(xml);
            Assert.AreEqual(d, deseredInstance);

            d = double.MaxValue;
            xml = ser.Serialize(d);
            deseredInstance = ser.Deserialize(xml); // Causes a System.OverflowException {"Value was either too large or too small for a Double."}
            Assert.AreEqual(d, deseredInstance);
        catch (Exception ex)
            Assert.Fail("No exception should have been throwned, but received:\r\n" + ex);
This is caused by the use of ToString without format specifier which does not guarantee that the deserialization of a serialized value is identical to the original value in the case of double, Single and BigInteger types. The format specifier "R" guarantees it. One way to fix the issue is by modifying the static method ToXmlValue in class XMLUtils with the following code (BigInterger section to be uncommented if .Net framework 4.0 or higher is used):
    public static string ToXmlValue(this object self)
        if (self is double)
            return ((double)self).ToString("R", CultureInfo.InvariantCulture);
        if (self is Single)
            return ((Single)self).ToString("R", CultureInfo.InvariantCulture);
        //if (self is BigInteger)
        //    return ((BigInteger)self).ToString("R", CultureInfo.InvariantCulture);
        return Convert.ToString((self ?? String.Empty), CultureInfo.InvariantCulture);

Closed Feb 13, 2015 at 12:04 AM by sina_iravanian
Applied the fix


sina_iravanian wrote Feb 13, 2015 at 12:02 AM

Hi. Thanks for reporting the problem and suggesting the fix. I applied pretty much the same fix on source code. Will create a new Nuget package later on. Thanks again.