[Solved] c# – What happens in memory when creating objects? [closed]


Assuming the “Student” type is a reference type (class), and not a value type (struct):

Student s = new Student();

Memory for a new Student object is allocated, and a new reference “s” is created and set to refer to the new memory.

Student s2 = s;

A new reference “s2” is created and set to refer to the same object and memory as “s”. No new object is created, and only enough memory is allocated to account for the reference.

s2 = new Student();

Memory for a new Student object is allocated. The “s2” reference is changed to refer to this new object. “s” still refers to the object created previously.

s = s2;

“s” is changed to refer to the object and memory created on the prior line. No new memory is allocated or released. However, there is now nothing referring the original object created on the first line. That object is no longer rooted. The next time the garbage collector runs, the object will be eligible for collection.

solved c# – What happens in memory when creating objects? [closed]