Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialise ReadOnlyDictionary?

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?

like image 479
Toby Avatar asked May 30 '17 12:05

Toby


People also ask

Is Readonlydictionary thread safe?

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.


1 Answers

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; 
like image 50
Camilo Terevinto Avatar answered Oct 09 '22 08:10

Camilo Terevinto