Why are the lists list1Instance
and p
in the Main
method of the below code pointing to the same collection?
class Person
In fact, IEnumerable
is already readonly. It means you cannot replace any items in the underlying collection with different items. That is, you cannot alter the references to the Person
objects that are held in the collection. The type Person
is not read only, however, and since it's a reference type (i.e. a class
), you can alter its members through the reference.
There are two solutions:
struct
as the return type (that makes a copy of the value each time it's returned, so the original value will not be altered — which can be costly, by the way)Person
type to accomplish this task.