开发者

How to reset a Dictionary

开发者 https://www.devze.com 2022-12-15 05:50 出处:网络
If I declared a dictionary li开发者_运维百科ke this: private static Dictionary<string, object> aDict = new Dictionary<string, object>();

If I declared a dictionary li开发者_运维百科ke this:

private static Dictionary<string, object> aDict = new Dictionary<string, object>();

And now I want to use it at another place. How do I reset it?

aDict = new Dictionary<string, object>(); // like this?

aDict = null; // or like this?

or other reset styles?


You can simply use the Clear method, it will remove all keys and values, then you can reuse it without having to create new instances:

aDict.Clear();


Try this

aDict.Clear();


aDict.Clear(); will work.


aDict.Clear(); is the only way to go since you don't want to change the reference and keep the same object available at another place


As everybody has pretty much answered that .Clear() method provided on the Dictionary class should be the way to go here (can't agree more).

Just to make it clear (for newbies of course ;)) that why not the other approaches, like creating a new instance every time we need to refresh the dictionary

aDict = new Dictionary<string, object>(); // like this?

because even though this way works, it is not a memory efficient approach as this creates a new instance and leaves behind the old instance(s) of the dictionary waiting for GC (garbage collector) to dispose it (as it is no longer referred). So you would agree on not consuming extra memory when you don't need to :)

and

aDict = null; // or like this?

because this leaves your instance set to null and next time as the OP wanted to use it as a dict, OP has to create another instance (yes, you got it right not memory efficient) and also this won't be a better programming style here as someone might end up doing .ContainsKey() (or any operation on the dictionary for that matter)on the aDict variable and cause a nullPointerException if aDict is still pointing to a null object.

Hope this explanation helps!! Thanks for reading!


Running a decompile of the Clear method in Resharper on a Dictionary object shows this:

/// <summary>Removes all keys and values from the <see cref="T:System.Collections.Generic.Dictionary`2" />.</summary>
[__DynamicallyInvokable]
public void Clear()
{
  if (this.count <= 0)
    return;
  for (int index = 0; index < this.buckets.Length; ++index)
    this.buckets[index] = -1;
  Array.Clear((Array) this.entries, 0, this.count);
  this.freeList = -1;
  this.count = 0;
  this.freeCount = 0;
  ++this.version;
}

The dictionary contains an integer array of buckets and other control variables that are either set to -1 or 0 to effectively clear the keys and values from the dictionary object. It is pretty many variables representing a valid state of the Dictionary as we can see in the .NET source code. Interesting.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号