Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to dispose a list

I am having List object. How can I dispose of the list?

For example,

List<User> usersCollection =new List<User>();  User user1 = new User(); User user2 = new User()  userCollection.Add(user1); userCollection.Add(user2); 

If I set userCollection = null; what will happen?

foreach(User user in userCollection) {     user = null; } 

Which one is best?

like image 270
Vivekh Avatar asked Jul 06 '11 11:07

Vivekh


People also ask

Why use Dispose method in C#?

The dispose pattern is used for objects that implement the IDisposable interface, and is common when interacting with file and pipe handles, registry handles, wait handles, or pointers to blocks of unmanaged memory. This is because the garbage collector is unable to reclaim unmanaged objects.

Does garbage collector call Dispose C#?

The GC does not call Dispose , it calls your finalizer (which you should make call Dispose(false) ).

How do you Dispose of a class object in VB net?

Calling Dispose on the class will cause it to notify the file system that it no longer needs the file, and it may thus be made available to other entities. In general, if an object which implements IDisposable is abandoned without calling Dispose , some things which should get done, won't be. There is a mechanism in .


1 Answers

Best idea is to leave it to the garbage collector. Your foreach will do nothing since only the reference will be set to null not the element in the list. Setting the list to null could in fact cause garbage collection to occur later than it could have (see this post C#: should object variables be assigned to null?).

like image 114
Cornelius Avatar answered Sep 29 '22 11:09

Cornelius