// Collection of code snippets by Arne Vajhøj // (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) using System; using System.Collections.Frozen; using System.Collections.Generic; public class C { public int V { get; set; } } public class Froz12 { public static void Main(string[] args) { IDictionary d1 = new Dictionary { ["A"] = new C { V = 123 } }; d1.Add("B", new C { V = 456 }); Console.WriteLine("{0} {1}", d1["A"].V, d1["B"].V); IDictionary d2 = d1.AsReadOnly(); try { d2.Add("C", new C { V = 0 }); } catch(NotSupportedException) { Console.WriteLine("You can't add or remove entries in readonly dictionary"); } d1.Add("C", new C { V = 0 }); // but you can add to or remove from underlying dictionary Console.WriteLine("{0} {1} {2}", d2["A"].V, d2["B"].V, d2.ContainsKey("C")); IDictionary d3 = d1.ToFrozenDictionary(); try { d3.Add("D", new C { V = 0 }); } catch(NotSupportedException) { Console.WriteLine("You can't add or remove entries in frozen dictionary"); } d1.Add("D", new C { V = 0 }); // changes to underlying dictionary are ignored Console.WriteLine("{0} {1} {2} {3}", d3["A"].V, d3["B"].V, d3.ContainsKey("C"), d3.ContainsKey("D")); } }