Reputation: 23
I am using C# to write a list that will contain unique instances of a class. I want to write a function that adds a single instance of this class and return a pointer to it.
public class Marble
{
public Marble(int ID)
{
// Initialize based on unique ID
}
}
public class Bag
{
private List<Marble> marbles = new List<Marble>();
public Marble Add(int ID)
{
Marble m = new Marble(ID);
marbles.Add(m);
return m;
}
}
It seems this would be more optimized than adding a new Marble and searching for the matching ID. However, will Marble m go out of scope when returning? As I understand Lists, it is merely a dynamic array of pointers. If Marble m ceases to exist, will the list's pointer no longer be valid?
Upvotes: 1
Views: 261
Reputation: 203812
will Marble
m
go out of scope when returning?
Yes, it absolutely will. It's a local variable of that method; it's scope is for that method invocation, so when the method returns that variable is out of scope. It so happens that, in this particular case, the lifetime of that variable also ends when that variable returns, so that variable will be able to be cleaned up at that point in time. In theory it's possible for the lifetime of the variable to be different from its scope, but it isn't in this case in this one example. See this article for a detailed analysis of the difference.
As I understand Lists, it is merely a dynamic array of pointers. If Marble m ceases to exist, will the list's pointer no longer be valid?
It will absolutely be valid. Losing the variable m
just means that that one reference no longer exists; it doesn't mean that the object that the variable's reference refers to no longer exists.
To use an analogy, think of the variable as a piece of paper. You write an address on that piece of paper. Next you burn that pieces of paper into ashes. What happens to your house? Nothing happens to your house; destorying that one reference to it in no way affects the house; if you have the house's address for some other reason (say you copied the address to a different piece of paper before burning it) you can still find the house, and destroying the paper in no way damages the house.
Upvotes: 0
Reputation: 1552
No, the list pointer will be just fine. The list holds a reference to the Marble object you created, and as long as the list holds this reference, without any intervention from you, the reference will always be valid.
Also, if you for some reason decide to remove the reference from the list, and nothing else is referencing it, then the reference will become something like a dangling pointer and will be automatically collected by the garbage collector, so you don't need about the clean up in your case either.
Remember that your Marble instance is a reference type, and this how it is supposed to work.
It might sound like magic for someone that is used to a language like C, where what you did would be a problem unless Marble was placed in the heap (via new, malloc and their kind).
Upvotes: 2