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?
Bagthat's being referenced somewhere, that instance should have the list of marblesMarble mwill be a reference type - it won't go out of scope when it's returned from the method. See this article by Jon Skeet for more information - jonskeet.uk/csharp/references.htmlreturn mwill return the pointer and m will not be destroyed until you are done with it.