Question

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?

Was it helpful?

Solution

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);

OTHER TIPS

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);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top