This post will discuss how to clone a Dictionary<TKey,TValue> in C#.

1. Using Dictionary<TKey,TValue>.ToDictionary() Method

To get a copy of a dictionary with keys associated with their corresponding values, you can use LINQ’s ToDictionary() method, as demonstrated below:

Download  Run Code

Output:

[White, #FFFFFF], [Grey, #808080], [Silver, #C0C0C0], [Black, #000000]

 
The above version creates a shallow copy of dictionary values. If you need to create a to deep copy of Dictionary<TKey,TValue> values, you can have TValue implement ICloneable and invoke its Clone() method.

2. Using Dictionary<TKey,TValue> Constructor

Alternatively, you can use the constructor of the Dictionary<TKey,TValue> class, which can take another instance of the same class and copy the object. The following example performs a shallow copy operation on dictionary values using its constructor.

Download  Run Code

Output:

[White, #FFFFFF], [Grey, #808080], [Silver, #C0C0C0], [Black, #000000]

That’s all about cloning a Dictionary<TKey,TValue> in C#.