Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add an object list to itself?

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:

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?

like image 600
SinOfficial Avatar asked Jun 02 '18 15:06

SinOfficial


People also ask

Can you add an object to a list?

Yes, but you must work with the former account object, otherwise you will override the reference when assigning a new object.

How to add objects into list in c#?

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.

How to add string into list string in c#?

To add string values to a list in C#, use the Add() method.


1 Answers

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.

like image 61
Mohammed Noureldin Avatar answered Oct 24 '22 15:10

Mohammed Noureldin