C
C# Learner
<code>
public class MainClass
{
private ArrayList list;
public Class()
{
list = new ArrayList();
AddToList();
ReadFromList();
}
private void AddToList()
{
list.Add(new RecordClass("test1"));
list.Add(new RecordClass("test2"));
list.Add(new RecordClass("test3"));
}
private void ReadFromList()
{
if (((RecordClass)list[0]).Field == "test1") {
// do something
}
if (((RecordClass)list[1]).Field == "test2") {
// do something
}
if (((RecordClass)list[2]).Field == "test3") {
// do something
}
}
}
public class RecordClass
{
private string field;
public RecordClass(string field)
{
this.field = field;
}
public string Field
{
get { return field; }
set { field = value; }
}
}
</code>
Now, when i read the list in ReadFromList(), are the list items
*guaranteed* to reference valid RecordClass instances, or would the
garbage collector free the memory that these references should be
pointing to?
I really can't understand how the GC would work in this case. If the
answer to the above question is "yes", then does the GC know to free
up the memory if I were to call ArrayList.Delete()?
Of course, if the answer to the first question is "no", then I'd have
to use a struct instead of a class for RecordClass, right -- since
it's a value type?
TIA
public class MainClass
{
private ArrayList list;
public Class()
{
list = new ArrayList();
AddToList();
ReadFromList();
}
private void AddToList()
{
list.Add(new RecordClass("test1"));
list.Add(new RecordClass("test2"));
list.Add(new RecordClass("test3"));
}
private void ReadFromList()
{
if (((RecordClass)list[0]).Field == "test1") {
// do something
}
if (((RecordClass)list[1]).Field == "test2") {
// do something
}
if (((RecordClass)list[2]).Field == "test3") {
// do something
}
}
}
public class RecordClass
{
private string field;
public RecordClass(string field)
{
this.field = field;
}
public string Field
{
get { return field; }
set { field = value; }
}
}
</code>
Now, when i read the list in ReadFromList(), are the list items
*guaranteed* to reference valid RecordClass instances, or would the
garbage collector free the memory that these references should be
pointing to?
I really can't understand how the GC would work in this case. If the
answer to the above question is "yes", then does the GC know to free
up the memory if I were to call ArrayList.Delete()?
Of course, if the answer to the first question is "no", then I'd have
to use a struct instead of a class for RecordClass, right -- since
it's a value type?
TIA