2

So, I am designing a global constant which would hold data for different characters for the program. I think System.Collections.Generic.Dictionary is my data type here, as it allows very quick searches by character. The declaration looks like this:

public static readonly Dictionary<char, LetterImage> letters;

(LetterImage being a custom struct. It's contents are not important.)

The problem? How do I define the elements of the Dictionary? I cannot just letters.Add('a', new LetterImage{...})because the dictionary is readonly, as I don't want a global variable. I need a way to initialize it with a literal.

dukc
  • 121
  • 1
  • 9

1 Answers1

8

You can use the apropriate collection to make sure the dictionary is truly readonly, that is a ReadOnlyDictionary. And you can initialize it inline

public static readonly ReadOnlyDictionary<char, LetterImage> dictionary = new ReadOnlyDictionary<string, string>(new Dictionary<char, LetterImage>
{
    ['a'] = new LetterImage()
});

If you have more complex code to initialize the dictionary, you could also use a static constructor (you can assign readonly fields in a static constructor)

class Program
{
    public static readonly ReadOnlyDictionary<char, LetterImage> dictionary;
    static Program()
    {
        var mutable = new Dictionary<char, LetterImage>();
        // Initalize
        dictionary = new ReadOnlyDictionary<char, LetterImage>(mutable)
    }
}

Note the readonly modifier does not impact the mutability of the object stored in the field. If you store a normal dictionary in a readonly field, you can still mutate the dictionary, you just can modify the field.

Titian Cernicova-Dragomir
  • 230,986
  • 31
  • 415
  • 357
  • A verbose thing to do, but probably the best as it does exactly what I want. Thank you. – dukc Feb 28 '18 at 07:44