Consider the following test program in which I (ab)use a dictionary to contain a document which may have unknown fields (and unknown types for those fields) ,
using System;
using System.Linq;
using System.Collections.Generic;
using Newtonsoft.Json;
public class Program
{
public static void Main()
{
var docs = GetDocuments();
foreach(var doc in docs){
doc["a"] = new string[]{"Hello", "World!"};
var docInLoop = JsonConvert.SerializeObject(doc);
Console.WriteLine(docInLoop);
}
var serialized = JsonConvert.SerializeObject(docs);
Console.WriteLine("===========================================================================================");
Console.WriteLine(serialized);
Console.WriteLine("===========================================================================================");
var bar = docs.First()["a"] as string[];
Console.Write("First entry of first document is string[]?");
Console.WriteLine(bar==null? " No" : "Yes");
}
public static IEnumerable<Document> GetDocuments(){
return Enumerable.Range(0, 10).Select(i => {
var doc = new Document();
doc["a"] = new int[]{1,2,3,4,5,6};
return doc;
});
}
public class Document : Dictionary<string, object>{}
}
When running this, the expectation is that since in the foreach
loop I modify the document the collection of documents should be modified. But here is the output:
{"a":["Hello","World!"]}
{"a":["Hello","World!"]}
{"a":["Hello","World!"]}
{"a":["Hello","World!"]}
{"a":["Hello","World!"]}
{"a":["Hello","World!"]}
{"a":["Hello","World!"]}
{"a":["Hello","World!"]}
{"a":["Hello","World!"]}
{"a":["Hello","World!"]}
===========================================================================================
[{"a":[1,2,3,4,5,6]},{"a":[1,2,3,4,5,6]},{"a":[1,2,3,4,5,6]},{"a":[1,2,3,4,5,6]},{"a":[1,2,3,4,5,6]},{"a":[1,2,3,4,5,6]},{"a":[1,2,3,4,5,6]},{"a":[1,2,3,4,5,6]},{"a":[1,2,3,4,5,6]},{"a":[1,2,3,4,5,6]}]
===========================================================================================
First entry of first document is string[]? No
Judging by the deserialization of the collection, mutating the document in the loop has no effect? How is this possible? What am I missing? I have a direct reference to the document object in the loop...