Dictionary.Clear will delete (but not delete) all the elements in the instance, while new Dictionary() will create a completely new instance that just turns out to be empty. There may be some subtle consequences between them. Consider the following examples.
void Example1() { var collection = new Dictionary<string, string>(); collection.Add("key1", "value1"); collection.Add("key2", "value2"); foreach (var kvp in collection) { collection = new Dictionary<string, string>(); Console.WriteLine(kvp); } } void Example2() { var collection = new Dictionary<string, string>(); collection.Add("key1", "value1"); collection.Add("key2", "value2"); foreach (var kvp in collection) { collection.Clear(); Console.WriteLine(kvp); } }
In the first example, the entire contents of the source collection will be printed. This is because the enumerator was created from a reference variable before it was reassigned to a new instance.
In the second example, the collection is cleared during enumeration, which will result in an InvalidOperationException because the collection has been modified.
Brian Gideon Sep 09 '09 at 16:11 2009-09-09 16:11
source share