I have an unchanging dictionary that is exposed in a class.
Currently my code looks like
using System.Collections.Generic; using System.Collections.ObjectModel; public class FooClass { private static ReadOnlyDictionary<string, byte> _validRevisions = new ReadOnlyDictionary<string, byte>( new Dictionary<string, byte>() { { "1.0", 0x00 }, { "1.1", 0x01 }, { "1.2", 0x02 }, { "1.3", 0x03 } } ); public static ReadOnlyDictionary<string, byte> ValidRevisions => _validRevisions; // other FooClass contents... }
I've used the backing field _validRevisions
as I could not figure out a better way of creating a shared constant dictionary property. Is there neater way to manage this or maybe I should just make the field public?
My main question being is there a shorter way to initialise the _validRevisions
field itself? Creating a Dictionary inline to pass it into a Dictionary (that happens to be read only) seems a bit... of a code smell. Is it? Is there a better way?
EDIT: one more thing about the ROD I just noticed, there are no methods to support checking if it contains a given value... is there a reason for that related to it' read-only-ness?
Yes you can assume it will only be initialized once. Concern 2: There is no need to worry about thread safety when you are only reading data which is never being updated by anthing. In your example the States of the US won't change too often (at least I hope not) and you can safetly read them from any thread you want.
If you don't mind having an IReadOnlyDictionary
instead of a ReadOnlyDictionary
, you could use this, since Dictionary
implements IReadOnlyDictionary
:
private static IReadOnlyDictionary<string, byte> _validRevisions = new Dictionary<string, byte> { { "1.0", 0x00 }, { "1.1", 0x01 }, { "1.2", 0x02 }, { "1.3", 0x03 } }; public static IReadOnlyDictionary<string, byte> ValidRevisions => _validRevisions;
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