We have a serialization issue which only happens in .NET 4.5 - same code works fine in .NET 4. we\'re trying to serialize an inherited type with a few fields, both base and
I recently had the same issue, and found the actual cause and the proper solution.
This problem is caused by the XML serializer testing the default value of a property/field. If the field value matches the DefaultValue attribute, it will not serialize it to save space. There is no overload for DefaultValue of type "decimal", so a decimal value will be converted to a float, which is one of the overloads.
You have to explicitly tell the attribute it is a decimal:
[DevaultValue(typeof(decimal), "1.56")]
Be aware that using DefaultValue on a field will not set that field to that value on deserialization. You still have to set the correct value in your constructor, or as a field initializer:
[DefaultValue(typeof(decimal), "1.56")]
decimal MyValue { get; set; } = 1.56;
We're looking to address this issue in upcoming .NET Framework 4.5 Update. I'll update the post with the download link as soon as update is released. Please contact netfx45compat at Microsoft dot com if you have mission critical app that's impacted, and fix is required urgently. I can help direct you to Microsoft support that can help with your request.
I had a also such a serialization failure. In my case it was caused by a type mismatch of the [DefaultValue(..)]
attributes. I had an attached default value of "1.0d"
(a double) for a property of type decimal
. It seems that the new implementation of the XmlSerializer can't convert such values anymore but the old one could. There is also the option to switch back to the old version of XmlSerializer by adding an attribute in 'App.config' but this is not recommended by Microsoft (and me). Hope this helps someone.
In 4.5, the implementation of XmlSerializer was replaced with one that isn't dependent on the C# compiler. While it provides better startup performance and stability, you might be running into a compatibility issue between the implementations. Can you try adding the following to your app.config file and see if that fixes the issue?
<configuration>
<system.xml.serialization>
<xmlSerializer useLegacySerializerGeneration="true"/>
</system.xml.serialization>
</configuration>
If you're concerned about having this work on 4.0, you could try detecting the version of the framework at runtime, and dynamically change the configuration if the runtime is 4.5 or higher. I wrote a blog post a while back explaining how to do that:
http://blogs.msdn.com/b/youssefm/archive/2010/01/21/how-to-change-net-configuration-files-at-runtime-including-for-wcf.aspx
I looked at your types more closely, and the problem is likely caused by a conflict between:
public virtual object @Value
{
}
on the Base and:
private new object Value
{
}
on the Derived class. Here are two things I would try: