Say I have a struct defined as such
struct Student
{
int age;
int height;
char[] name[12];
}
When I’m reading a binary file, it looks something like
List<Student> students = new List<Student>();
Student someStudent;
int num_students = myFile.readUInt32();
for (int i = 0; i < num_students; i++)
{
// read a student struct
}
How can I write my struct so that I just need to say something along the lines of
someStudent = new Student();
So that it will read the file in the order that the struct is defined, and allow me to get the values as needed with syntax like
someStudent.age;
I could define the Student as a class and have the constructor read data and populate them, but it wouldn’t have any methods beyond getters/setters so I thought a struct would be more appropriate.
Or does it not matter whether I use a class or struct? I’ve seen others write C code using structs to read in blocks of data and figured it was a “good” way to do it.
If you want to serialize / deserialize the struct
If you want to read/write the entire struct to a binary file (serialization), I suggest you look at
https://stackoverflow.com/a/629120/141172
Or, if it is an option for you, follow @Marc’s advice and use a cross-platform serializer. Personally I would suggest protobuf-net which just happens to have been written by @Marc.
If you are loading from an arbitrary file format
Just like a class, a struct can have a constructor that accepts multiple parameters. In fact, it is generally wise to not provide setters for a struct. Doing so allows the values of the struct to be changed after it is constructed, which generally leads to programming bugs because many developers fail to appreciate the fact that struct is a value type with value semantics.
I would suggest providing a single constructor to initialize your struct, reading the values from the file into temporary variables, and then constructing the struct with a constructor.
To dig further into the perils of mutable structs (ones that can be changed after initialized) I suggest
Why are mutable structs “evil”?