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?
Another idea for this post... If you were wanting to ensure that all members of a collection are properly disposed, you could use the following extension method:
This looks through the collection for any member that implements
IDisposable
and disposing of it. From your executing code, you could clean up the list like this:This will ensure that all members get the chance to release resources and the resulting list is empty.
Best way is
Than GC will take care of rest.
I don't agree that you shouldn't do anything if you don't need the objects in the list anymore. If the objects implement the interface
System.IDisposable
then the designer of the object thought that the object holds scarce resources.If you don't need the object anymore and just assign null to the object, then these scarce resources are not freed until the garbage collector finalizes the object. In the mean time you can't use this resource for something else.
Example: Consider you create a bitmap from a file, and decide you don't need neither the bitmap, nor the file anymore. Code could look like follows:
The good method would be:
The same accounts for objects in a list, or any collection. All objects in the collection that are IDisposable should be disposed. Code should be like:
Or if you want to create an IEnumerable extension function
All lists / dictionaries / read only lists / collections / etc can use these methods, because they all implement IEnumerable interface. You can even use it if not all items in the sequence implement System.IDisposable.
As everyone has mentioned leave to GC, its the best option and don't force the GC. Setting the variable to null will mark the variable for the GC.
if your after more info: Best Practice for Forcing Garbage Collection in C#
Yet another example of an extension method you can use to dispose a list of objects which implement the IDisposable interface. This one uses LINQ syntax.
If your item in list is un-managed object then you can call Dispose() on every object by iterating it.
If the list object is managed object then you need not do anything. GC will take care.