Consider the following C# code where two variables reference the same list. What will be printed?
using System; using System.Collections.Generic; class Program { static void Main() { List<int> listA = new List<int> {1, 2, 3}; List<int> listB = listA; listB.Add(4); Console.WriteLine(string.Join(",", listA)); } }
Think about what happens when two variables point to the same list and one changes it.
Both listA and listB point to the same list in memory. Adding 4 via listB changes the original list, so printing listA shows the updated list with 4.
Look at this C# code where two variables reference the same object. What will be printed?
using System; class Person { public string Name; } class Program { static void Main() { Person p1 = new Person { Name = "Alice" }; Person p2 = p1; p2.Name = "Bob"; Console.WriteLine(p1.Name); } }
Remember that objects are reference types in C#.
Both p1 and p2 point to the same Person object. Changing Name via p2 changes the same object, so p1.Name is also "Bob".
What will this C# program print?
using System; class Program { static void ModifyArray(int[] arr) { arr[0] = 100; } static void Main() { int[] numbers = {1, 2, 3}; ModifyArray(numbers); Console.WriteLine(string.Join(",", numbers)); } }
Arrays are reference types in C#. What happens when you change an element inside a method?
The array numbers is passed by reference. Changing arr[0] inside ModifyArray changes the original array, so the first element becomes 100.
What will this C# code print?
using System; using System.Collections.Generic; class Program { static void Main() { List<int> original = new List<int> {1, 2, 3}; List<int> clone = original; clone.Add(4); Console.WriteLine(string.Join(",", original)); } }
Assigning one list to another copies the reference, not the list itself.
Both original and clone point to the same list. Adding 4 to clone changes the original list, so printing original shows 1,2,3,4.
Consider this C# code. What will be printed?
using System; using System.Collections.Generic; class Program { static void Main() { var dict1 = new Dictionary<string, List<int>>(); dict1["key"] = new List<int> {1, 2}; var dict2 = dict1; dict2["key"].Add(3); Console.WriteLine(string.Join(",", dict1["key"])); } }
Dictionaries and lists are reference types. What happens when you modify a list inside a shared dictionary?
Both dict1 and dict2 reference the same dictionary. The list at key "key" is also shared. Adding 3 modifies the list, so printing dict1["key"] shows 1,2,3.