I am having 2 scinarios to show the issue.
Scenario 1
using System;
using Newtonsoft.Json.Linq;
public class Program
{
public static void Main()
{
var arr = new JArray();
arr.Add("apple");
var obj = new JObject();
obj["arr"] = arr;
obj["arr"] = arr;
arr.Add("mango");
foreach(var a in obj["arr"]){
Console.WriteLine(a);
}
}
}
Here obj["array"]
should be referenceing the arr
, i.e. initialized earlier. So the output should be
apple
mango
but the output was
apple
Scenario 2
using System;
using Newtonsoft.Json.Linq;
public class Program
{
public static void Main()
{
var arr = new JArray();
arr.Add("apple");
var obj = new JObject();
obj["arr"] = arr;
var obj2 = new JObject();
obj2["arr"] = arr;
arr.Add("mango");
foreach(var a in obj2["arr"]){
Console.WriteLine(a);
}
}
}
Similarly obj2["arr"]
should be referencing the arr
. but it is not.
So the expected output is
apple
mango
but the output is
apple
I am not that proficient in csharp. Please let me know if i am missing something here.
Edit
Adding another scenario as mentioned by @Wyck in comments.
Scenario 3
using System;
using Newtonsoft.Json.Linq;
public class Program
{
public static void Main()
{
var arr = new JArray();
Console.WriteLine(arr.GetHashCode());
arr.Add("apple");
var obj = new JObject();
obj["arr"] = arr;
Console.WriteLine(obj["arr"].GetHashCode());
obj["arr"] = arr;
Console.WriteLine(obj["arr"].GetHashCode());
obj["arr"] = arr;
Console.WriteLine(obj["arr"].GetHashCode());
arr.Add("mango");
foreach(var a in obj["arr"]){
Console.WriteLine(a);
}
}
}
Repeating the assignment obj["arr"] = arr
odd number of time gets back the original reference of arr
but doing so even number of times doesn't.
The output of this will be
10465620
10465620
1190878
10465620
apple
mango
see the hash code is changed for even number assignment. for the odd number assignment it again became as before.