Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Shallow copy Dictionary?

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?

like image 300
Georges Oates Larsen Avatar asked Jan 14 '12 00:01

Georges Oates Larsen


1 Answers

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); 
like image 139
JaredPar Avatar answered Sep 21 '22 16:09

JaredPar