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 type
System.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?
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With