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.
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.
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