I have a list of disposable items that I add to a collection that already contains several disposable items. I am completing the code in an attempt ... to finally block so that if an exception is thrown when copying elements from the list to the collection, all objects in the list are deleted correctly:
private static void LoadMenuItems(ApplicationMenu parent) { List<ApplicationMenuItem> items = null; try { items = DataContext.GetMenuItems(parent.Id); foreach (var item in items) { parent.Items.Add(item); } items = null; } finally { if (items != null) { foreach (var item in items) { item.Dispose(); } } } }
If an exception occurs after adding several objects to the collection, I will have a situation where the collection contains some objects. This can cause those located objects to be deleted again in the next attempt ... catch block:
try {
So, I am looking for possible solutions to stop Dispose () being called twice. I have a solution, but I thought I would give it to the community to find out if there are any alternatives.
source share