30

I need to shallow copy a dictionary in c#.

For instance:

Dictionary<int,int> flags = new Dictionary<int,int>();
flags[1] = 2;
flags[2] = 3;
flags[0] = 9001;
Dictionary<int,int> flagsn = flags.MemberwiseClone();

Unfortunately, that returns the error: "error CS1540: Cannot access protected member object.MemberwiseClone()' via a qualifier of typeSystem.Collections.Generic.Dictionary'. The qualifier must be of type `PointFlagger' or derived from it"

Not entirely sure what this means... Is there another way to shallow copy a dictionary/fix my code above?

Georges Oates Larsen
  • 6,812
  • 12
  • 51
  • 67

2 Answers2

62

To get a shallow copy, just use the constructor of Dictionary<TKey, TValue> as it takes an IEnumerable<KeyValuePair<TKey, TValue>>. It will add this collection into the new instance.

Dictionary<int, int> flagsn = new Dictionary<int, int>(flags);
JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
  • 1
    @Jared, Actually, it seems it doesn't accept an `IEnumerable`, but a `IDictionary dictionary` –  Mar 10 '16 at 08:31
10

This is a generic way I found where you don't have to explicitly write any type, which I prefer for maintainability reasons:

var ShallowCopy = OriginalDictionary.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
gatopeich
  • 3,287
  • 31
  • 26
  • What is "kvp => kvp.Key, kvp => kvp.Value" in this context. How will i add key and value. It showing an error at my end – Pratik Jul 30 '13 at 04:56
  • 2
    You need to add a using statement for `System.Linq` to access the ToDictionary() extension method. – Johnathon Sullinger Aug 12 '14 at 02:23
  • I would strongly advise against doing this. The LINQ call is useful for deep copying, but has huge negative performance implications if all you want is a shallow copy. – Dmitri Nesteruk Feb 22 '21 at 10:09