[CSHARP-4591] AutoMap constructors for mutable classes also Created: 30/Mar/23  Updated: 03/Apr/23

Status: Backlog
Project: C# Driver
Component/s: Serialization
Affects Version/s: 2.19.1
Fix Version/s: None

Type: New Feature Priority: Unknown
Reporter: Robert Stam Assignee: Unassigned
Resolution: Unresolved Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Issue Links:
Related
related to CSHARP-4586 Projections not retrieving expected f... Closed

 Description   

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.


Generated at Wed Feb 07 21:48:42 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.