Is it safe to write the following code?
private static readonly IReadOnlyDictionary<string, string> Map = new Dictionary<string, string>
{
["A"] = "AAA",
["B"] = "BBB",
["C"] = "CCC"
};
I know ConcurrencyDictionary
is the standard way for achieving thread safety for dictionaries. But since all that I need is a "constant" map which I never intend to modify, is it 100% safe to initialize a readonly IReadOnlyDictionary static field?
What matters for thread safety is the actual type of the object (Dictionary), not the type of the variable (IReadOnlyDictionary).
According to the documentation:
A
Dictionary<TKey, TValue>
can support multiple readers concurrently, as long as the collection is not modified.
Therefore, your code is fine — assuming, of course, that no one casts your variable back to Dictionary and modifies it. If you're concerned about that possibility, then wrap your Dictionary in a ReadOnlyDictionary.
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