Imagine this struct
:
struct Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
And following code :
var list = new List<Person>();
list.Add(new Person { FirstName = "F1", LastName = "L1" });
list.Add(new Person { FirstName = "F2", LastName = "L2" });
list.Add(new Person { FirstName = "F3", LastName = "L3" });
// Can't modify the expression because it's not a variable
list[1].FirstName = "F22";
When I want to change Property
's value it gives me the following error:
Can't modify the expression because it's not a variable
While, when I tried to change it inside an array such as Person[]
it worked without any error.Is there any problem with my code when using with generic collections?
struct
. When you genuinely need to use astruct
, you'll know it. MakePerson
aclass
instead. – CafardGeneral rule of thumb is to never use struct
? – Overloadstruct
for types that are very small, short-lived, and immutable for performance reasons (source), or if you simply have a need for value semantics. You probably won't see this situation come up too often, if at all. Always useclass
unless you have a specific reason to be using astruct
. – Cafard