-
Type: New Feature
-
Resolution: Unresolved
-
Priority: Unknown
-
None
-
Affects Version/s: 2.19.1
-
Component/s: Serialization
-
None
Automapping the following class has unexpected results:
private class D { public D(int x) { X = x; } public int X { get; } public int Y { get; set; } }
When an instance of D is serialized only the Y property is serialized:
var d = new D(1) { Y = 2 }; var json = d.ToJson();
The result is:
{ Y : 2 }
This is because constructors are currently only automapped if the class is immutable, and D is not immutable.
And read-only properties are only automapped if the class is immutable and the property matches an argument of a mapped constructor. Since D is mutable the constructor was not mapped.
Most likely we should automap constructors for all classes. If a class has a constructor we should use it during deserialization.
The reason we decided not to do this a long time ago was that it was considered a breaking change. We added support for automapping constructors as part of adding support for immutable classes. Since immutable classes were previously not supported it was not considered a breaking change to use constructors when deserializing immutable classes.
But mutable classes have always been deserialized by creating an uninitialized object and calling all the property setters with the deserialized value. There is a remote possibility that calling a constructor would break deserialization if the constructor throws an exception that would not occur if the property setter is called instead. Maybe this concern is unwarranted, and we should always use constructors if they are present, regardless of whether the class is immutable or not.
- related to
-
CSHARP-4586 Projections not retrieving expected fields after upgrading to 2.19 driver
- Closed