2

Imagining i have :

List<MyObject> MyList = new List<MyObject>();
MyObject obj1 = new MyObject();
MyObject obj2 = new MyObject();
MyList.Add(obj1);
MyList.Add(obj2);

Does a

MyList.Clear();

Delete the instantiated : 'obj1','obj2' ? Or are they kept in the memory but the list is just now empty ?

Hamid Pourjam
  • 20,441
  • 9
  • 58
  • 74
Fortune
  • 523
  • 1
  • 7
  • 21
  • 1
    The objects are still alive, but the list is empty. Objects are removed by the Garbage Collector (GC) as soon as there is no reference to it anymore. – MichaelS Nov 03 '14 at 13:30

3 Answers3

1

as far as you have a reference to an object and you can access it in your code it is there in memory and garbage collector is not collecting it. so the answer is NO, they are kept in the memory

you can read more about garbage collection here.

if the code was like this

List<MyObject> MyList = new List<MyObject>();
MyList.Add(new MyObject());
MyList.Add(new MyObject());

then when you call MyList.Clear() you have no reference to your created MyObjects so garbage collector will collect them and delete them from memory in it's next run. if you want to remove obj1 and obj2 from memory after clearing list you should use

obj1 = null;
obj2 = null;
GC.Collect()

but be aware of consequences of forcing garbage collection.

Hamid Pourjam
  • 20,441
  • 9
  • 58
  • 74
0

the clear function just clear the list. obj1 and obj2 will not be null. you can easily check it by printing the objects:

Console.WriteLine(obj1);
Stephan Bauer
  • 9,120
  • 5
  • 36
  • 58
No Idea For Name
  • 11,411
  • 10
  • 42
  • 70
0

Delete the instantiated : 'obj1','obj2' ? Or are they kept in the memory but the list is just now empty ?

They are kept in the memory until there are no reference to your objects and GC deletes them. In this case only your list will be empty.You can easily test this by trying to access members of your object after calling Clear method.

Selman Genç
  • 100,147
  • 13
  • 119
  • 184