I was wondering what would happen if I added a list to itself. Maybe a stack overflow, maybe a compiler error?
List<object> lstobj = new List<object>();
lstobj.Add(lstobj);
So I executed the code and checked the local variables:
The list seems to contain an infinite number of list instances. Why is there no stack overflow? Are the lists just pointers to the original list? But even if the lists are just pointers, do pointers not also occupy memory too?
Yes, but you must work with the former account object, otherwise you will override the reference when assigning a new object.
Add() method adds an object to the end of the List<T>. List. AddRange() method adds a collection of objects to the end of the List<T>. The following code example adds three int objects to the end of the List<int> using Add method.
To add string values to a list in C#, use the Add() method.
It would not be a problem. List is reference type, i.e., you will get a reference to the list inside itself (exactly what you showed).
So what you see (that big hierarchy) is only in Visual Studio. The real situation is just you get a reference to the memory address of that array inside the same memory address of the same array. Therefore, you get stack overflow.
You would see that a lot in Navigation properties when using Entity framework.
It would be a problem if you tried to serialize the list without configuring the serializer to be aware when serializing the circular references.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With