Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing an Array of Structs in C#

Tags:

arrays

c#

struct

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}     }; }; 
like image 503
Adam Tegen Avatar asked Nov 21 '08 17:11

Adam Tegen


People also ask

How do you initialize an array of structures?

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

Can you create an array of structs in C?

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.

What is the correct way of initialising an array in C?

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.

How are structs initialized in C?

Structure members can be initialized using curly braces '{}'. For example, following is a valid initialization.


1 Answers

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

like image 187
Jon Skeet Avatar answered Sep 26 '22 16:09

Jon Skeet