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

How should BsonValues be serialized for C# null?

    • Type: Icon: Improvement Improvement
    • Resolution: Done
    • Priority: Icon: Minor - P4 Minor - P4
    • 2.0
    • Affects Version/s: 1.8.3
    • Component/s: None
    • None
    • Minor Change

      The C# driver currently serializes BsonValues with a C# null value as { _csharpnull : true }. For example, given a class:

      public class C
      {
          public int Id;
          public BsonValue V;
      }
      

      The following test:

      Console.WriteLine(new C { Id = 1, V = null }.ToJson());
      Console.WriteLine(new C { Id = 2, V = BsonNull.Value }.ToJson());
      

      results in:

      { "_id" : 1, "V" : { "_csharpnull" : true } }
      { "_id" : 2, "V" : null }
      

      The difference is important, because otherwise if we serialized a C# null as a BsonNull then when deserialized the value would change to something else (it would no longer be a C# null, it would now be an instance of BsonNull).

      The driver currently treats ALL BsonValues the same way, including properties that are declared as subclasses of BsonValue.

      The question has been raised as to whether we should abandon this consistency and represent C# null using BsonNull in cases where BsonNull couldn't be a valid value. For example, suppose you had a different class:

      public class D
      {
          public int Id;
          public BsonDateTime V;
      }
      

      This class differs from C only in that the data type of V is now BsonDateTime instead of BsonValue.

      Currently, the following code:

      Console.WriteLine(new D { Id = 1, V = null }.ToJson());
      Console.WriteLine(new D { Id = 2, V = DateTime.Now }.ToJson());
      

      also results in:

      { "_id" : 1, "V" : { "_csharpnull" : true } }
      { "_id" : 2, "V" : ISODate("2013-11-20T20:49:07.992Z") }
      

      although it could be argued that the { _csharpnull : true } encoding is not strictly necessary since during deserialization we could figure out that a BSON null must represent a C# null since a property of type BsonDateTime is not assignment compatible with BsonNull.Value.

      So the question posed in this ticket is:

      1. Is it better to be consistent, as we currently are, and serialize all BsonValue subclasses the same way (with respect to C# null)?
      2. Or is it better to only use the less intuitive { _csharpnull : true } representation only in those cases where it is required to disambiguate between C# null and BsonNull?

            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: