Say I have a list of Person
objects (List<Person>
) called persons
, like this:
class Person
{
public int PersonId { get; set; } // Unique ID for the person loaded from database
public string Name { get; set; }
}
// In a different class
public List<Person> Persons = new List<Person>(); // Person objects are subsequently added to the list
and then I select some of the Person
objects from the list, sort them by a property (e.g. by each person's unique ID PersonId
), and add these selected Person
objects to another list called selectedPersons
.
I now need to edit the properties of a Person
object that is in selectedPersons
, but these changes need to be made to the original copy of this Person
object in persons
. I currently only know the index of this person in the selectedPersons
list, so can I simply edit the person in the selectedPersons
list and have the changes made to that person reflected in the original persons
list, like this:
selectedPersons[selectedPersonIndex].Name = "John";
or do I have to edit the original Person
object in the persons
list by first finding the index of the person the persons
list using the person's ID, like this:
persons[FindPersonIndexById(selectedPersons[selectedPersonIndex].BookingId).Name = "John";
where FindPersonIndexById
returns the index of the person in persons
whose ID matches the ID given.
I know lists are reference types in C#, but, when objects from one list are added to another list, I wasn't sure whether changes made to objects in the second list are automatically made to the same objects in the first list.
When you have a list of objects that are reference types and not value types, that is stored in the list is a reference for each object in the list. Hence if you add the same object to two different lists, you actually add to the second list the same reference. Hence if you make any change in the object, this would be "visible" from both lists.