Uploaded image for project: 'C# Driver'
  1. C# Driver
  2. CSHARP-4591

AutoMap constructors for mutable classes also

    • Type: Icon: New Feature New Feature
    • Resolution: Unresolved
    • Priority: Icon: Unknown 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.

            Assignee:
            Unassigned Unassigned
            Reporter:
            robert@mongodb.com Robert Stam
            Votes:
            0 Vote for this issue
            Watchers:
            1 Start watching this issue

              Created:
              Updated: