Wednesday, 30 November 2011

c# how to dispose objects of Dictionary

 
problem

c# dispose objects of Dictionary
you cannot dispose the object of a Dictionary with "foreach" process, you can do with "while" getting the Enumerator of the Dictionary.
difficulty level

5/10 :|
compatibility

c#
solution

In the follow example, I scan serially a Dictionary generic of <string, IInDataObject> type and I dispose its hosted objects.
Each object in the dictionary, each Value is IInDataObject interface. This interface implements IDisposable so can call Dispose();

//get the Enumerator in order to scan with while (and not with foreach)
System.Collections.IEnumerator enumerator = dataObjectList.GetEnumerator();
//perform the Enumerator in while loop
while (enumerator.MoveNext()) {
    //get the pair of Dictionary
    KeyValuePair<string, IInDataObject> pair =
        ((KeyValuePair<string, IInDataObject>)(enumerator.Current)); 
    //dispose it
    pair.Value.Dispose();
       
}

No comments:

Post a Comment