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?
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.
The GC does not call Dispose , it calls your finalizer (which you should make call Dispose(false) ).
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 .
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?).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With