-
Type: Bug
-
Resolution: Done
-
Priority: Major - P3
-
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>()); });
- is related to
-
CSHARP-765 DOCS: Convention for ignoring all empty collection types in serialization?
- Closed