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} }; };
If you have multiple fields in your struct (for example, an int age ), you can initialize all of them at once using the following: my_data data[] = { [3]. name = "Mike", [2]. age = 40, [1].
The most common use of structure in C programming is an array of structures. To declare an array of structure, first the structure must be defined and then an array variable of that type should be defined.
The initializer for an array is a comma-separated list of constant expressions enclosed in braces ( { } ). The initializer is preceded by an equal sign ( = ). You do not need to initialize all elements in an array.
Structure members can be initialized using curly braces '{}'. For example, following is a valid initialization.
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:
class SomeClass { struct MyStruct { private readonly string label; private readonly int id; public MyStruct (string label, int id) { this.label = label; this.id = id; } public string Label { get { return label; } } public string Id { get { return id; } } } static readonly IList<MyStruct> MyArray = new ReadOnlyCollection<MyStruct> (new[] { new MyStruct ("a", 1), new MyStruct ("b", 5), new MyStruct ("q", 29) }); }
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<>
.)
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