Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Differences between Dictionary.Clear and new Dictionary()

What are the key differences between Dictionary.Clear and new Dictionary() in C#? Which one is recommended for which cases?

like image 573
Newbie Avatar asked Sep 09 '09 15:09

Newbie


People also ask

How to reset a dictionary in c#?

The Dictionary. Clear() method in C# removes all key/value pairs from the Dictionary<TKey,TValue>.

What is difference between Array and list and dictionary in C#?

An Array is collection of elements. Arrays are strongly typed collections of the same datatypes and these arrays ar a fixed length that cannot be changed during runtime. Array lists are not strongly typed collections. They will store values of different datatypes or the same datatype.

What is dictionary advantages of dictionary in C#?

In C#, Dictionary is a generic collection which is generally used to store key/value pairs. The working of Dictionary is quite similar to the non-generic hashtable. The advantage of Dictionary is, it is generic type. Dictionary is defined under System. Collection.


1 Answers

Dictionary.Clear() will remove all of the KeyValue pairs within the dictionary. Doing new Dictionary() will create a new instance of the dictionary.

If, and only if, the old version of the dictionary is not rooted by another reference, creating a new dictionary will make the entire dictionary, and it's contents (which are not rooted elsewhere) available for cleanup by the GC.

Dictionary.Clear() will make the KeyValue pairs available for cleanup.

In practice, both options will tend to have very similar effects. The difference will be what happens when this is used within a method:

void NewDictionary(Dictionary<string,int> dict) {    dict = new Dictionary<string,int>(); // Just changes the local reference }  void  ClearDictionary(Dictionary<string,int> dict) {    dict.Clear(); }  // When you use this... Dictionary<string,int> myDictionary = ...; // Set up and fill dictionary  NewDictionary(myDictionary); // myDictionary is unchanged here, since we made a new copy, but didn't change the original instance  ClearDictionary(myDictionary); // myDictionary is now empty 
like image 59
Reed Copsey Avatar answered Sep 20 '22 04:09

Reed Copsey