Summary
.NET Core apps fail to XML serialize an object which contains an enum value, while .NET Framework (4.7.2) succeeds. Is this a known breaking change, and if so, how can I work around it?
Code Example
The following console application does not throw an exception in .NET Framework 4.7.2 project:
public enum MyEnum
{
One,
}
public class ValueContainer
{
public object Value;
}
class Program
{
static void Main(string[] args)
{
XmlSerializer newSerializer = XmlSerializer.FromTypes(
new[] { typeof(ValueContainer)})[0];
var instance = new ValueContainer();
instance.Value = MyEnum.One;
using (var memoryStream = new MemoryStream())
{
newSerializer.Serialize(memoryStream, instance);
}
}
}
The exact same code in a .NET Core 3.0 Console Application throws the following exception when calling Serialize
:
System.InvalidOperationException
HResult=0x80131509
Message=There was an error generating the XML document.
Source=System.Private.Xml
StackTrace:
at System.Xml.Serialization.XmlSerializer.Serialize(XmlWriter xmlWriter, Object o, XmlSerializerNamespaces namespaces, String encodingStyle, String id)
at System.Xml.Serialization.XmlSerializer.Serialize(Stream stream, Object o, XmlSerializerNamespaces namespaces)
at System.Xml.Serialization.XmlSerializer.Serialize(Stream stream, Object o)
at CoreXml.Program.Main(String[] args) in C:\Users\vchel\source\repos\CoreXml\CoreXml\Program.cs:line 28
Inner Exception 1:
InvalidOperationException: The type CoreXml.MyEnum may not be used in this context.
Am I doing something wrong in my code? Is this a breaking change between .NET Framework and .NET Core?
Is there a workaround?
Update
I should have pointed out that when serializing in .NET 4.7.2, I get the following (desired) output for Value:
<Value xsi:type="xsd:int">0</Value>
I would like whatever solution is proposed for .NET Core to also output the same XML, as I need to maintain compatibility with existing files and older versions of the app which aren't using .NET Standard.
Update 2
I should have included this information in the original question, but now that I'm attempting to implement an answer, I see that there are a few requirements I didn't think of at first.
First, the object which is being serialized is also being used in logic, and the logic depends on the object stored in the value being an enumeration. Therefore, converting the value permanently to an integer (such as by casting in a setter) will impact the logic of the application so it's something I can't do.
Second, even though my example has been simplified to show a difference between .NET Framework and .NET Core, the real application uses many enumerations. Therefore, the solution should allow multiple enumeration values to be used.