The code is:
struct m1
{
public int a;
public int b;
}
int main()
{
List <m1> mList;
m1.initialize;
//new. and add some items to it.
now I want to access the objects in mList at first I tried:
for each(m1 it in mList)
{
m1.a = 5;
}
but it failed. becuase after the for each I wrote m1.first().a on console. it was it's initialized value not 5.
then I tried
for (int counter = 0; counter < mList.size(); counter++)
{
m1 it = mList[counter];
it.a = 5;
}
again the same problem.
then I tried
for (int counter = 0; counter < mList.size(); counter++)
{
mList[counter].a = 5;
}
it even didn't compiled. it gives me an error. it says something about not being modifiable return value of list.this[int].
then I tried
for (int counter = 0; counter < mList.size(); counter++)
{
var m1 it = mList[counter];
it.a = 5;
}
it didn't work too. I tried all I could and everything that I found in internet and this site. Could you please help you to find a way to access parameters of objects(of type struct) in list? Obviously it is easy when list is made from objects(from classes). it comes to complication if I want to made a list from objects of structs. Any help would highly welcomed.
The problem is that you've put a struct in a list. When you fetch it from the list, that will create a copy - so modifying it won't do any good. Given your comments, it's possible that you're confused about how value types and reference types work in C#, in which case I suggest you read my article on the topic (or books, or MSDN etc).
You'd need to fetch it, modify the copy, then replace the value in the list:
However, I would strongly advise against creating mutable value types in the first place, partly because they cause exactly this sort of problem. Value types should usually be used for more "fundamental" values which can't be changed in place. It doesn't make sense to change what "the number 5" means, for example, or "January 1st at 10am". If you change the meaning, you've got a new value - so force that to genuinely be a new value.
It's unclear (due to lack of context) whether you should be creating an immutable value type and replacing it in the list, or creating a mutable reference type (a class) instead. Or possibly even an immutable reference type, as that can often aid readability.
I'd also advise against using public fields - use properties instead, to separate implementation details from the type's API.
Try this:
if you are interesting to work with struct without using a temporary variable: use a struct collection: