I know that we should rather be using dictionaries as opposed to hashtables. I cannot find a way to clone the dictionary though. Even if casting it to ICollection which I do to get the SyncRoot, which I know is also frowned upon.
I am busy changing that now. Am I under the correct assumption that there is no way to implement any sort of cloning in a generic way which is why clone is not supported for dictionary?
The dict. copy() method returns a shallow copy of the dictionary. The dictionary can also be copied using the = operator, which points to the same object as the original. So if any change is made in the copied dictionary will also reflect in the original dictionary.
Dictionary in . NET represents a collection of key/value pairs. In this tutorial, learn how to create a dictionary, add items to a dictionary, remove items from a dictionary, and other dictionary operations using C# and . NET. C# Dictionary class is a generic collection of keys and values pair of data.
In C#, Dictionary is a generic collection which is generally used to store key/value pairs. The working of Dictionary is quite similar to the non-generic hashtable. The advantage of Dictionary is, it is generic type. Dictionary is defined under System.
Use the Constructor that takes a Dictionary. See this example
var dict = new Dictionary<string, string>(); dict.Add("SO", "StackOverflow"); var secondDict = new Dictionary<string, string>(dict); dict = null; Console.WriteLine(secondDict["SO"]);
And just for fun.. You can use LINQ! Which is a bit more Generic approach.
var secondDict = (from x in dict select x).ToDictionary(x => x.Key, x => x.Value);
Edit
This should work well with Reference Types, I tried the following:
internal class User { public int Id { get; set; } public string Name { get; set; } public User Parent { get; set; } }
And the modified code from above
var dict = new Dictionary<string, User>(); dict.Add("First", new User { Id = 1, Name = "Filip Ekberg", Parent = null }); dict.Add("Second", new User { Id = 2, Name = "Test test", Parent = dict["First"] }); var secondDict = (from x in dict select x).ToDictionary(x => x.Key, x => x.Value); dict.Clear(); dict = null; Console.WriteLine(secondDict["First"].Name);
Which outputs "Filip Ekberg".
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