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

Don't create uninitialized objects during deserialization

    • Type: Icon: Improvement Improvement
    • Resolution: Unresolved
    • Priority: Icon: Major - P3 Major - P3
    • None
    • Affects Version/s: 2.11.3
    • Component/s: Serialization
    • Labels:
      None

      The current implementation of BsonClassMap (used by BsonClassMapSerializer) in certain scenarios can fall back to creating uninitialized objects using FormatterServices.GetUninitializedObject:

      https://github.com/mongodb/mongo-csharp-driver/blob/v2.11.3/src/MongoDB.Bson/Serialization/BsonClassMap.cs#L1294

      Since this bypasses calling the constructors it means any code in the constructors will not be executed, which means there is a high risk that the instantiated object is not properly initialized.

      During deserialization we already try to call the constructor that takes the most arguments . If no matching constructor taking arguments is found we then call the no-argument constructor (if it exists).

      There doesn't seem to really be a use case for using GetUninitializedObject. The risk of creating improperly initialized objects is just too great.

      Even in the probably extremely rare case where a user has a class that can only be deserialized using GetUninitializedObject, the workaround if we stop using GetUninitializedObject is as simple as adding a no-argument constructor. If a no-argument constructor already exists we wouldn't be calling GetUninitializedObject anyway.

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

              Created:
              Updated: