Search code examples
json.netxmlserializerdatacontractserializerserialization

why do we need to prevent Circular Object References


I'm new to this. Can you please explain to me why the "Circular REference" is a bad thing, what's the bad result it may bring about?


Solution

  • If you would serialize this into JSON then you would get an infinite JSON-document because at the time the Serializer serializes the CTest object into JSON and he reaches the Other property this property is referenced by itself and the serializer starts with serializing this object. And so one.

    public class CTest
    {
        public CTest Other { get; set; }
        public string Description { get; set; }
    }
    
    [Test]
    public void Circulartest()
    {
        CTest instance = new CTest();
        instance.Description = "Hello";
        instance.Other = instance;
    
        JsonConvert.SerializeObject(instance);
    }
    

    This would result in following JSON file

    {
        "Description": "Hello"
        "Other":
        {
            "Description": "Hello"
            "Other":
            {
                "Description": "Hello"
                "Other":
                {
                    "Description": "Hello"
                    "Other":
                    {
                        ....never ending story
                    }
                }
            }
        }
    }