Modify property of object in List [Answered]
I have a struct like this:
And I have a
List<MyStruct>
. I want to modify MyProperty
for a certain MyStruct
in the list, using the Id
property. I tried this:
But it didn't work.5 Replies
MyStruct is a struct so you can't change the value of properties
Loop or not
Ir you need to edit the properties, make it a class to make it a reference type
$ref
Yes, use a class if you want mutable properties. In general structs should be immutable.
Now, knowing that a struct is passed by value (meaning a copy is made when you access it), you COULD achieve what you want even using structs - by mutating the copy and then putting that copy back into the list.
However, this is doing a bunch of extra work for no good reason - just use a class instead.
You could also achieve this with ref locals if the data was an array instead of a list. Again though, I would just use a class or a record.
Thanks
✅ This post has been marked as answered!