Using structs in C# to read data - c#

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.

There is not, AFAIK, a low-level direct-layout struct reader built into .NET. You would want want to look at BinaryReader, reading each field in turn? Basically, ReadInt32() twice, and ReadChars(). Pay particular attention to the encoding of the character data (ASCII? UTF8? UTF-16?) and the endianness of the integers.
Personally, I'd look more at using a dedicated cross-platform serializer!

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.
public stuct MyStruct
{
public int Age { get; private set; }
public int Height { get; private set; }
private char[] name;
public char[] Name
{
get { return name; }
set
{
if (value.Length > 12) throw new Exception("Max length is 12");
name = value;
}
}
public MyStruct(int age, int height, char[] name)
{
}
}
To dig further into the perils of mutable structs (ones that can be changed after initialized) I suggest
Why are mutable structs “evil”?

Related

How to make struct immutable inside a class definition

I have a question about creating an immutable struct inside a class definition. I want to define the struct outside the class but use that same struct type in the class definition while maintaining immutability. Will the code below achieve this?
namespace space
{
class Class1
{
public Struct {get; set;}
}
public Struct
{
public Struct(string strVar)
{
StructVar = strVar;
}
public string StructVar {get;}
}
}
Also, if I have a struct within a struct like:
class Class1
{
public Struct2 {get; set;}
}
public struct Struct2
{
public Struct2(string str, InStruct inStrct)
{
StrVar = str;
InStruct = inStrct;
}
public string StrVar {get;}
public InStruct InStruct {get;}
}
public struct InStruct
{
public InStruct(Array ary)
{
StrArray = ary
}
public Array StrArray {get;}
}
Does this also maintain immutability?
Lastly, if the size of the array in the InStruct is likely to be quite long, should I not use a struct at all and just put the array itself into the class definition instead? Am I just going struct crazy?
My concern is that because I'm doing a {set;} in the class definition that I'm breaking a rule somewhere. I would put the struct in the class definition itself but I didn't like to have to continuously call class constructors over and over to create each struct, that kind of seemed to defeat the purpose of using a struct in the first place.
It's a little difficult to give a complete answer without understanding exactly what you are trying to accomplish, but I'll start with a few important distinctions.
First, in C#, the struct/class distinction isn't about mutability per se. You can have a immutable class, like this one
public class CannotBeMutated
{
private string someVal;
public CannotBeMutated(string someVal)
{
_someVal = someVal
}
public string SomeVal => _someVal;
}
and a mutable struct, like this one
// This is not at all idiomatic C#, please don't use this as an example
public struct MutableStruct
{
private string _someVal;
public MutableStruct(string someVal)
{
_someVal = someVal;
}
public void GetVal()
{
return _someVal
}
public void Mutate(string newVal)
{
_someVal = newVal;
}
}
Using the above struct I can do this
var foo = new MutableStruct("Hello");
foo.mutate("GoodBye");
var bar = foo.GetVal(); // bar == "GoodBye"!
The difference between structs and classes is in variable passing semantics. When an object of a value type (e.g. a struct) is assigned to a variable, passed as a parameter to or returned from a method (including a property getter or setter) a copy of the object is made before it is passed to the new function context. When a object of a reference type is passed as a parameter to or returned from a method, no copy is made, because we only pass a reference to the object's location in memory, rather than a copy of the object.
An additional point on struct 'copying'. Imagine you have a struct with a field that is a reference type, like this
public struct StructWithAReferenceType
{
public List<string> IAmAReferenceType {get; set;}
}
When you pass an instance of this struct into a method, a copy of the reference to the List will be copied, but the underlying data will not. So if you do
public void MessWithYourSruct(StructWithAReferenceType t)
{
t.IAmAReferenceType.Add("HAHA");
}
var s = new StructWithAReferenceType { IAmAReferenceType = new List()};
MessWithYourSruct(s);
s.IAmAReferenceType.Count; // 1!
// or even more unsettling
var s = new StructWithAReferenceType { IAmAReferenceType = new List()};
var t = s; // makes a COPY of s
s.IAmAReferenceType.Add("hi");
t.IAmAReferenceType.Count; // 1!
Even when a struct is copied, its reference type fields still refer to the same objects in memory.
The immutable/mutable and struct/class differences are somewhat similar, insofar as they are both about where and whether you can change the contents of an object in your program, but they are still very distinct.
Now on to your question. In your second example, Class1 is not immutable, as you can mutate the value of Struct2 like this
var foo = new Class1();
foo.Struct2 = new Struct2("a", 1);
foo.Struct2 // returns a copy of Struct2("a", 1);
foo.Struct2 = new Struct2("b", 2);
foo.Struct2 // returns a copy of Struct2("b", 2);
Struct2 is immutable, as there is no way for calling code to change the values of StrVar or InVar once. InStruct is similarly immutable. However, Array is not immutable. So InStruct is an immutable container for a mutable value. Similar to if you had a ImmutableList<List<string>>. While you can guarantee calling code does not change the value of InStruct.StrArray to a different array, you can do nothing about calling code changing the value of the objects in the Array.
Finally, some generic advice related to your example.
First, mutable structs, or structs with mutable fields, are bad. The examples above should point to why structs with mutable fields are bad. And Eric Lippert himself has a great example of how terrible mutable structs can be on his blog here
Second, for most developers working in C# there's almost never a reason to create a user defined value type (i.e. a struct). Objects of value types are stored on the stack, which makes memory access to them very fast. Objects of reference types are stored on the heap, and so are slower to access. But in the huge majority of C# programs, that distinction is going to be dwarfed by the time cost of disk I/O, network I/O, reflection in serialization code, or even initialization and manipulation of collections. For ordinary developers who aren't writing performance-critical standard libraries, there's almost no reason to think about the performance implications of the difference. Heck, developers in Java, Python, Ruby, Javascript and many other languages get by in languages totally without user-defined value types. Generally, the added cognitive overhead they introduce for developers is almost never worth any benefit you might see. Also, remember that large structs must be copied whenever they are passed or assigned to a variable, and can actually be a performance problem.
TL;DR you probably shouldn't use structs in your code, and they don't really have anything to do with immutability.

Assigning value to member of nullable struct in C#

In C#, I have a struct like this:
public struct Slab
{ public float[] sizeM;
public string textureSrc;
//more members, not relevant here...
}
And another like this:
public struct Tombstone
{ public Slab mainSlab;
public Slab? basing;
//more...
}
Now, I want to modify members of basing:
uiState[0].stone.basing.Value.sizeM[2] = Int32.Parse(breadthField.Value) / 100.0f;
uiState[0].stone.basing.Value.textureSrc = fileName;
(uiState[0].stone is of type Tombstone)
First of these two calls works correctly, as I'm just changing a member of the array in basing, not the array itself. However, the second complains:
Cannot modify the return value of 'Slab?.Value' because it is not a variable
It works if I do the same to mainSlab which is not nullable. Is there a way to do this without copying the whole basing to a local variable for changes?
Is there a way to do this without copying the whole basing to a local variable for changes?
No, because Nullable<T> doesn't provide direct access to the underlying value field. You can't modify it "in place".
There are all kinds of little issues like this when you use mutable structs. I'd strongly advise you to use classes or immutable structs whenever possible, to avoid these corner cases.
Frankly, the main error here is almost certainly: having a mutable struct. Now, there are scenarios where mutable structs make sense, but those scenarios are narrow, and this almost certainly isn't one of them.
Frankly, your code will be much easier to rationalize if you stop doing that; with recent C#, you can even use readonly struct to help enforce this (and to get better behaviour with in):
public readonly struct Slab
{ public readonly float[] sizeM;
public readonly string textureSrc;
//more members, not relevant here...
}
(personally I'd also consider properties instead of public fields, but that is a separate issue)
Then it becomes obvious that you can only assign the entire object:
Slab? foo = ...
... some logic
foo = new Slab(size, textureSource); // perhaps taking new values from the old
The only other alternative is basically to do the same thing anyway:
Slab? foo = ...
// ...
var innerVal = foo.GetValueOrDefault(); // or .Value if you've already null-checked
// ...
innerVal.textureSrc = ...
foo = innerVal;
There may be many possible fixes for this "problem", depending on the rest of your design and requirements... For example:
public struct Tombstone
{
public Slab mainSlab;
public Slab basing;
public bool hasBasing => basing.sizeM != null;
//more...
}
To be honest I never user Nullables... Nullable value types, what's next, global rvalues?

Equivalent (or better) C# structures to C++ structures

I am a C++ programmer moving to C# (so complete newb really). So far its a pretty easy transition :)
I am porting some code (well, re-writing it) from C++ to C#. I am stuck with lots of possibilities on how to port the following C++ STL structures. Here is a C++ code snippet of my C++ structure layout (I have not bothered showing the enums to save on clutter, but I can add if required):
struct DeviceConnection_t
{
DeviceType_e device;
DeviceState_e state;
bool isPass;
DeviceConnection_t() :
device(DEV_TYPE_UNKNOWN),
state(DEV_STATE_DISCONNECTED),
isPass(false)
{}
};
struct Given_t
{
std::string text;
std::vector<DeviceConnection_t> deviceConnections;
};
struct Action_t
{
ActionEventType_e type;
uint32_t repeat_interval;
uint32_t repeat_duration;
DeviceType_e device;
bool isDone;
Action_t() :
type(AE_TYPE_UNKNOWN),
repeat_interval(0),
repeat_duration(0),
device(DEV_TYPE_UNKNOWN),
isDone(false)
{}
};
struct When_t
{
std::string text;
std::multimap<uint32_t, Action_t> actions; // time, action
};
So here I have a vector of DeviceConnection_t, which I have read here: c-sharp-equivalent-of-c-vector-with-contiguous-memory can just be made into a C# List<DeviceConnection_t>. That seems to work, so far so good.
Next is my multimap<int, Action_t> where the int is a time value where duplicate entries are expected/allowed.
I read here: multimap-in-net that there is no equivalent in C#, but there are various implementations out there.
So I could use one of these, but other questions I read like: order-list-by-date-and-time-in-string-format got me thinking there might be a better way to achieve what I want.
What I really want is:
1.A list of Action_t in time order - where time could be an element of Action_t (I removed it as a element in my c++ because it became my multi-map key). I also need to be able to search through the collection to find time values.
2. Some sort of default constructor to populate the default values of a newly instantiated struct, but I can't see how this is done either.
I really like the look of the Dictionary C# class, but I don't think that fits any of my requirements at the moment (might be wrong here).
So my two questions are:
What is the best way to create a time ordered collection of objects?
How can I assign default values to a new instance of a structure? (in the same way a default constructor does in C++)?
By using struct, it is impossible to enforce initial values. No explicit default constructor can be provided and in case of default construction, all values will be initialized with their default value. It is only possible to provide additional constructors, where fields can be initialized. In the example, if AE_TYPE_UNKNOWN and DEV_TYPE_UNKNOWN would be 0, then default initialization would actually be equivalent to your values.
struct Action_t
{
// example constructor, but there will always be a default constructor
public Action_t(ActionEventType_e type, DeviceType_e device)
{
this.type = type;
this.device = device;
this.isDone = false;
this.repeat_interval = 0;
this.repeat_duration = 0;
}
public ActionEventType_e type;
public UInt32 repeat_interval;
public UInt32 repeat_duration;
public DeviceType_e device;
public bool isDone;
}
If you need to enforce initialization with values that differ from the default, then you need to create a class, where explicit initialization is possible.
class Action_t
{
public ActionEventType_e type = ActionEventType_e.AE_TYPE_UNKNOWN;
public UInt32 repeat_interval = 0;
public UInt32 repeat_duration = 0;
public DeviceType_e device = DeviceType_e.DEV_TYPE_UNKNOWN;
public bool isDone = false;
}
However, for more flexibility I'd advice to use public properties, either as auto properties or as public properties with private backing field. Depending on your choice and used language standard version, you have different options how to write the properties and the initialization:
class Action_t
{
public Action_t()
{
repeat_interval = 0;
}
public UInt32 repeat_interval { get; set; }
private UInt32 _repeat_duration = 0;
public UInt32 repeat_duration
{
get { return _repeat_duration; }
set { _repeat_duration = value; }
}
public bool isDone { get; set; } = false; // valid for C# 6
}
You should read into the differences between struct and class in C#, since there are some mayor differences that you may not expect as a C++ programmer, where struct is basically a public-default class. Then decide, if struct is suited for your case.
The best equivalent to a sorted multimap would probably be a SortedDictionary<key, ICollection<values>> with an add method that handles new keys / adding to existing keys.
IDictionary<DateTime, ICollection<Action_t>> actions = new SortedDictionary<DateTime, ICollection<Action_t>>();
void AddAction(DateTime key, Action_t action)
{
ICollection<Action_t> values;
if (!actions.TryGetValue(key, out values))
{
values = new List<Action_t>();
actions[key] = values;
}
values.Add(action);
}
Unfortunately C# doesn't seem to have a sorted List. The Dictionary is fine if you have Key, Value pairs.
1) If its just a collection (List) you can take a look at the discussion here:
Is there a SortedList<T> class in .NET?. Otherwise you can manually sort the collection(I named it sort in my example) like:
actions.Sort((x, y) => x.time.CompareTo(y.time));
In this your time object should be a IComparable or a primitive, but you can replace "x.time.CompareTo" to any other sorting method. (Based on: List<> OrderBy Alphabetical Order).
If you use a list you can just search the collection with linq:
actions.First(x=>x.time.certainValue == DesiredValue);
But there are many functions to search through the tree. There are some displayed: https://msdn.microsoft.com/en-us/library/system.linq.enumerable_methods(v=vs.110).aspx
2) There are multiple ways to do this. First off, the default constructor:
Action_t() {
type=AE_TYPE_UNKNOWN;
repeat_interval=0;
repeat_duration=0;
device= DEV_TYPE_UNKNOWN);
isDone = false;
}
This works like any other code. But if all values are public Properties (Also a variable: https://msdn.microsoft.com/nl-nl/library/x9fsa0sw.aspx) then you can remove the constructor (or have a public one that you can access) and create new instances with:
new Action_t {
type=AE_TYPE_UNKNOWN,
repeat_interval=0,
repeat_duration=0,
device= DEV_TYPE_UNKNOWN),
isDone = false
}
The difference is where the variables are set. The default constructor is always safe.
I hope this answers your question!

Modify a List Inside of a Struct

I have been working on a project for my c# class at school. And I have a very simple question I think. But I have been unable to find an answer anywhere. I keep getting results about how to make a list of structs. I want to know how to access a list inside a struct?
So here is the struct given to us by our teacher and that we must use for this assignment:
[Serializable]
struct Name
{
public string firstName;
public string lastName;
}
[Serializable]
struct Movie
{
public string title;
public string year;
public Name director;
public float quality;
public string mpaaRating;
public string genre;
public List<Name> cast;
public List<string> quotes;
public List<string> keywords;
}
struct MovieList
{
public int length;
public Movie[] movie;
}
Now I have tried accessing quotes and keywords in the following two ways and both have produced errors:
1.
string quotes;
MovieList ML = new MovieList();
quotes = Console.ReadLine();
ML.movie[0].quotes[0] = quotes;
2.
string quotes;
MovieList ML = new MovieList();
quotes = Console.ReadLine();
ML.movie[0].quotes.Add(quotes);
A struct is a Value type and as such, using a struct to carry all of this information makes it very inefficient because every time you pass it as an argument the whole contents of the struct will need to be copied, etc. a better approach would be to use a Class, which is a Reference type and it's reference is what gets passed around.
As far as how to access your struct members, here's an example:
MovieList m =new MovieList();
m.movie = new Movie[10];
m.movie[0].title="The Girl with the Dragon Tatoo";
Console.WriteLine(m.movie[0].title); //The Girl with the Dragon Tatoo
UPDATE:
Showing how to access quotes:
MovieList m =new MovieList();
m.movie = new Movie[10];
m.movie[0].title="The Girl with the Dragon Tatoo";
m.movie[0].quotes = new List<string>();
m.movie[0].quotes.Add("Hello World");
Console.WriteLine(m.movie[0].title); //The Girl with the Dragon Tatoo
Console.WriteLine(m.movie[0].quotes[0]); //Hello World
Your MovieList struct contains an array of Movie. The array isn't being initialized.
Why not just make a List<Movie> instead of a separate struct or class?
thanks for being honest about your homework. The first problem I see is that you are trying to use the list before they are initialized. Inside the structures, brand-new list are referencing to null. You have to initialize them. Please do a research about struct initialization.
Make these classes rather than structs. For every Movie in your MovieList class you will have to create a new instance of Movie so you can add to the quotes list. Otherwise it wont be initialised.
Structures should generally avoid exposing fields or properties of mutable class types, except in cases where the struct will be used by code which is merely interested in the identity of the objects referred to therein, rather than their content. Suppose one has structures m1, which contains information about some movie, and m2, which is initially blank. If one executes code:
m2 = m1;
m2.year = 2012;
m2.keywords.Add("dinosaur")
Then m1.year will be unmodified, but m1.keywords will have "dinosaur" added to it (since m1.keywords and m2.keywords both refer to the same mutable List<string>.
It's fine for structs which are used as data-holders to expose read-write fields of logically-immutable class types, or value types which don't contain any mutable class types, but structs which hold mutable reference types often have weird semantics and should be avoided when practical.

How to set a specific member of a struct, using indexing in C#

Assuming I have a struct:
struct Vector
{
public int X, Y;
// ...
// some other stuff
}
and a class:
class Map
{
public Vector this[int i]
{
get
{
return elements[i];
}
set
{
elements[i] = value;
}
}
private Vector[] elements
// ...
// some other stuff
}
I want to be able to do something like: map[index].X = 0; but I can't, because the return value is not a variable.
How do I do this, if at all possible?
You should avoid mutable structs.
If you want your type to be mutable use a class instead.
class Vector
{
public int X { get; set; } // Use public properties instead of public fields!
public int Y { get; set; }
// ...
// some other stuff
}
If you want to use a struct, make it immutable:
struct Vector
{
private readonly int x; // Immutable types should have readonly fields.
private readonly int y;
public int X { get { return x; }} // No setter.
public int Y { get { return y; }}
// ...
// some other stuff
}
The compiler prevents you from doing this because the indexer returns a copy of an object not a reference (struct is passed by value). The indexer returns a copy, you modify this copy and you simply don't see any result. The compiler helps you avoid this situation.
If you want to handle such situation you should use class instead or change the way you deal with Vector. You shouldn't modify it's value but initialize it's values in constructor, more on this topic: Why are mutable structs “evil”?.
define Vector as class,
or
store value in a temporary variable
var v = map[index];
v.X = 0;
map[index] = v;
or
add function to change
map[index] = map[index].Offset()
or
let the [] operator return a setter class
class Setter { Vector[] Data; int Index; public double X { get { return Data[Index]; } set { Data[Index] = new Vector(value, Data[Index].Y); }}}
public Setter this[int i]
{
get
{
return new Setter() { Data = elements, Index= i };
}
}
Although generic classes work pretty well for many purposes, they do not provide any reasonable way to access structs by reference. This is unfortunate since in many cases a collection of structs would offer better performance (both reduced memory footprint and improved cache locality) and clearer semantics than a collection of class objects. When using arrays of structs, one can use a statement like ArrayOfRectangle[5].Width += 3; with very clear effect: it will update field X of ArrayOfRectangle[5] but it will not affect field X of any other storage location of type Rectangle. The only things one needs to know to be certain of that are that ArrayOfRectangle is a Rectangle[], and Rectangle is a struct with a public int field X. If Rectangle were a class, and the instance held in ArrayOfRectangle[5] had ever been exposed to the outside world, could be difficult or impossible to determine whether the instance referred to by ArrayOfRectangle[5] was also held by some other code which was expecting that field X of its instance wouldn't change. Such problems are avoided when using structures.
Given the way .net's collections are implemented, the best one can do is usually to make a copy of a struct, modify it, and store it back. Doing that is somewhat icky, but for structs that aren't too big, the improved memory footprint and cache locality achieved by using value types may outweigh the extra code to explicitly copy objects from and to the data structures. It will almost certainly be a major win compared with using immutable class types.
Incidentally, what I'd like to see would be for collections to expose methods like:
OperateOnElement<paramType>(int index, ref T element, ref paramType param, ActionByRef<T,paramType> proc) which would call proc with the appropriate element of the collection along with the passed-in parameter. Such routines could in many cases be called without having to create closures; if such a pattern were standardized, compilers could even use it to auto-generate field-update code nicely.

Categories