CSharp · Console
using System.Collections.Generic; //For Dictionary
using System.Collections.ObjectModel; //For ReadOnlyDictionary
public class Program
{
private static readonly Dictionary<string, int> testDict1 = new Dictionary<string, int>
{
{"One", 1},
{"Two", 2}
};
private static ReadOnlyDictionary<string, int> testDict2 = new ReadOnlyDictionary<string, int>(
new Dictionary<string, int>
{
{"One", 1},
{"Two", 2}
});
public static void Main()
{
//In a normal dictionary, the values can still be changed if it's declared as readonly
//readonly only protects the reference. So I can do this:
testDict1["One"] = -99; //Totally fine.
//But I can't do this:
//testDict1 = new Dictionary<string, int>();
//A ReadOnlyDictionary is the exact opposite in this regard.
//I can't change values:
//testDict2["One"] = -99; //Error
//But I can change the reference to a different object:
testDict2 = new ReadOnlyDictionary<string, int>(
new Dictionary<string, int>
{
{"One", -99},
{"Two", -99}
});
}
}