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

Serialization error for generic enumerable not implementing System.Collections.Generic.List

    • Type: Icon: Bug Bug
    • Resolution: Fixed
    • Priority: Icon: Unknown Unknown
    • 2.17.0
    • Affects Version/s: None
    • Component/s: Serialization
    • None
    • Minor Change

      Summary

      When a custom collection property is serialized, an exception is thrown because MongoDB.Bson default serialization provider implicitly assumes any IEnumerable<T> can be serialized as type List<T>.

      Version: v2.16.0

      How to Reproduce

      using MongoDB.Bson;
      using System.Collections;
      using System.Collections.Generic;
      
      namespace MongoDbBsonTest
      {
          public static class Program
          {
              public static void Main()
              {
                  var obj = new Node()
                  {
                      Children = new FooCollection()
                      {
                          new Node() { Prop = "Test" }
                      }
                  };
                  var bson = obj.ToBson<object>();
              }
          }
      
          public class Node
          {
              public string Prop { get; set; }
              public INodeCollection Children { get; set; }
          }
      
          public interface INodeCollection : ICollection<Node>
          {
          }
      
          public class FooCollection : INodeCollection
          {
              private readonly List<Node> data = new();
              public int Count => data.Count;
              public bool IsReadOnly => false;
              public void Add(Node item) => data.Add(item);
              public void Clear() => data.Clear();
              public bool Contains(Node item) => data.Contains(item);
              public void CopyTo(Node[] array, int arrayIndex) => data.CopyTo(array, arrayIndex);
              public IEnumerator<Node> GetEnumerator() => data.GetEnumerator();
              public bool Remove(Node item) => data.Remove(item);
              IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
          }
      } 

            Assignee:
            james.kovacs@mongodb.com James Kovacs
            Reporter:
            lee_mingyau@hotmail.com Ming Yau Lee
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

              Created:
              Updated:
              Resolved: