coder
coder

Reputation: 5

What happens in memory if multiple instances of a class are retrieved with the same variable name in C#

I have an instance of a class named person 1. What happens in memory if I get an instance with the same name again? can i use the first generated address when i create the object for the second time. Is a new address assigned in memory?

for (int i = 0; i < 4; i++)
   {
      Person person1 = new Person(); 
   }

Stack: person1 - 0x234567 memory adress

Heap: Person - 0x234567

Upvotes: 0

Views: 274

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1063338

In this specific case: the variable isn't used, so the compiler actually interprets this as a discard - it removes person1 entirely, just doing a pop on the result of the newobj, as though you'd done _ = new Person();. The objects created will be eligible for garbage collection at some indeterminate time.

In the more general case: it all depends on scopes, captures, etc; if the same "local" ends up being reused (which isn't absolutely guaranteed), then only the last value assigned will still be reachable, so: if nothing else roots the created objects, then once again: they will be eligible for garbage collection at some indeterminate time.

Upvotes: 2

Related Questions