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

Add an overload of SetDefaultValue that supports creating a new instance of the default value each time

    • Type: Icon: Bug Bug
    • Resolution: Done
    • Priority: Icon: Major - P3 Major - P3
    • 1.8.2
    • Affects Version/s: 1.8.1
    • Component/s: None
    • None
    • Fully Compatible

      There is a problem using SetDefaultValue with mutable classes, because nothing protects the default value from being changed. For example, assume that the default value for L has been set to an empty list:

      public class C
      {
          public int Id { get; set; }
          public List<int> L { get; set; }
      }
      
      BsonClassMap.RegisterClassMap<C>(cm =>
      {
          cm.AutoMap();
          cm.GetMemberMap(c => c.L).SetDefaultValue(new List<int>());
      });
      

      Then the following innocent looking code alters the default value:

      var c1 = BsonSerializer.Deserialize<C>("{ _id : 1 }");
      c1.L.Add(1);
      var c2 = BsonSerializer.Deserialize<C>("{ _id : 1 }");
      

      The call to c1.L.Add(1) has altered the default value, so c2 no longer has an empty list as the value of L.

      The proposed alternative is to provide an additional overload of SetDefaultValue that allows you to provide a delegate that will create a new instance of the default value each time. For example:

      BsonClassMap.RegisterClassMap<C>(cm =>
      {
          cm.AutoMap();
          cm.GetMemberMap(c => c.L).SetDefaultValue(() => new List<int>());
      });
      

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

              Created:
              Updated:
              Resolved: