How can I initialize a const / static array of structs as clearly as possible?
class SomeClass { struct MyStruct { public string label; public int id; }; const MyStruct[] MyArray = { {'a', 1} {'b', 5} {'q', 29} }; };
Firstly, do you really have to have a mutable struct? They’re almost always a bad idea. Likewise public fields. There are some very occasional contexts in which they’re reasonable (usually both parts together, as with
ValueTuple) but they’re pretty rare in my experience.Other than that, I’d just create a constructor taking the two bits of data:
Note the use of ReadOnlyCollection instead of exposing the array itself – this will make it immutable, avoiding the problem exposing arrays directly. (The code show does initialize an array of structs – it then just passes the reference to the constructor of
ReadOnlyCollection<>.)