I have a class declared as public class DatumSet : List<datum>, where
public struct datum {
public UInt32[] chan;
public UInt64 sample_number;
public float time;
public UInt32 source_sector;
}
I want to iterate through the List and make some changes. Why does this NOT work
for (int i = 0; i < this.Count; i++) {
this[i].sample_number = startSample;
this[i].time = (float)startSample / _sample_rate;
startSample++;
}
but this DOES work
for (int i = 0; i < this.Count; i++) {
datum d = this[i];
d.sample_number = sampleNumber;
d.time = (float)sampleNumber / _sample_rate;
sampleNumber++;
}
I get the error:
Cannot modify the return value of ‘System.Collections.Generic.List.this[int]’ because it is not a variable
You’re having problems because you are using a struct rather than a class.
When you retrieve a struct from a collection, a copy is made. Your first set of code gives you an error because it detects you’re doing something you may not mean to do. You’d actually be editing a copy of the struct rather than the copy in the collection.
The second doesn’t produce an error because you explicitly pull the copy out of the collection before editing. This code may compile, but won’t modify any of the structs in the collection and thus won’t give you the results that you’re expecting.