2 Answers
2

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.

I would suggest that you make all value types immutable; it helps to prevent you from getting into this mess. So either you can keep datum as a value type, and replace the value in the list on each iteration, or you can change it to be a class, and modify the objects via the reference stored in the list.

(Either way, I'd strongly suggest that you start using properties instead of public fields, and start following .NET naming conventions too.)

I was just about to comment, "where is Jon Skeet when you need him?"
–
Jason SperskeNov 20 '12 at 22:34

Hmm, this is new to me. Structs are mutable and classes are immutable? If I just changed the keyword 'struct' to 'class' would that be sufficient or do i have to add get/set methods too?
–
rezaNov 20 '12 at 22:45

@reza: The first thing to do is not treat C# like C :) They're completely different languages, and you should treat them differently. Ignore the fact that they both use braces and semi-colons, and learn C# from scratch, ideally from a good book. Don't just "look over" a document, tutorial or book - read them thoroughly, assuming that every sentence may contain something you didn't know before.
–
Jon SkeetNov 20 '12 at 23:09

1

@reza: Yes, that will fix it - but you should do more. You should fix your naming conventions, and you should avoid public fields which are the enemy of encapsulation... and you definitely should make sure you understand exactly why it will fix it, and why the compiler was complaining. Oh, and understand why the code you thought worked really wasn't working.
–
Jon SkeetNov 21 '12 at 6:43