Changing values elsewhere

suggest change
public static void Main(string[] args)
{
  var studentList = new List<Student>();
  studentList.Add(new Student("Scott", "Nuke"));
  studentList.Add(new Student("Vincent", "King"));
  studentList.Add(new Student("Craig", "Bertt"));

  // make a separate list to print out later
  var printingList = studentList; // this is a new list object, but holding the same student objects inside it

  // oops, we've noticed typos in the names, so we fix those
  studentList[0].LastName = "Duke";
  studentList[1].LastName = "Kong";
  studentList[2].LastName = "Brett";

  // okay, we now print the list
  PrintPrintingList(printingList);
}

private static void PrintPrintingList(List<Student> students)
{
  foreach (Student student in students)
  {
      Console.WriteLine(string.Format("{0} {1}", student.FirstName, student.LastName));
  }
}

You’ll notice that even though the printingList list was made before the corrections to student names after the typos, the PrintPrintingList method still prints out the corrected names:

Scott Duke
Vincent Kong
Craig Brett

This is because both lists hold a list of references to the same students. SO changing the underlying student object propogates to usages by either list.

Here’s what the student class would look like.

public class Student
{
    public string FirstName { get; set; }
    public string LastName { get; set; }

    public Student(string firstName, string lastName)
    {
        this.FirstName = firstName;
        this.LastName = lastName;
    }
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Value type vs Reference type:
* Changing values elsewhere

Table Of Contents
17 Regex
19 Arrays
21 Enum
22 Tuples
24 GUID
27 Looping
30 Value type vs Reference type
36 Casting
46 Methods
88 Events
92 Structs
104 Indexer
106 Stream
107 Timers
109 Threading
127 Caching
135 Pointers
147 C# Script