Implement IXmlSerializable in a readonly struct
14-Jun-2022
Xml serialization is really common. For a class this is done automatically, but not for your own struct. The primitive structs from Microsoft (bool, byte, short, int, long, double, decimal, etc.) don’t have this problem. The serialization and deserialization of those types are done by the XmlSerializer class. For your own struct you have to implement the IXmlSerializable interface. This isn’t really hard, but it is harder when the struct is a readonly struct. A feature which Microsoft added to C# 7.2 a few years ago. The problem is caused by the ReadXml() method of this interface. This method returns a void which means that you have to modify the fields inside the struct, which is not allowed if the struct is readonly. Luckily there is a solution using the Unsafe.AsRef() method. In this blog I will explain how to use it.