YamlDotNet
YamlDotNet copied to clipboard
Type safe serialization of primitives and System.Type
EnsureRoundtrip emits tags for objects when needed. But it does not force emission of tags for primitives.
For example the class
class Container
{
public object Data { get; set; } = 123L;
}
will be deserialized as string "123".
I could bypass the problem by appending a custom ChainedEventEmitter after the TypeAssigningEventEmitter.
However It was still not possible to properly deserialize the container when data was assigned an instance of System.Type. For example container.Data = typeof(long) is deserialized also as string because the SystemTypeConverter bypassed the ChainedEventEmitter and also does not emit a tag:
https://github.com/aaubry/YamlDotNet/blob/5ec2dd75704d6dced41c0d49ff5528f3797d1068/YamlDotNet/Serialization/Converters/SystemTypeConverter.cs#L30
I'd suggest to add a method like WithSystemTypeTagPrefix(string) to the serialization builder classes and always emit tags when the runtime type is not equal to the declared type.