0
0
C Sharp (C#)programming~10 mins

Common bugs from reference sharing in C Sharp (C#) - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to create a new list that does not share the reference with the original list.

C Sharp (C#)
List<int> original = new List<int> {1, 2, 3};
List<int> copy = original[1];
copy.Add(4);
Console.WriteLine(original.Count);
Drag options to blanks, or click blank then click option'
A.ToList()
B.Add()
C.Clear()
D.RemoveAt(0)
Attempts:
3 left
💡 Hint
Common Mistakes
Using methods that modify the original list instead of copying it.
2fill in blank
medium

Complete the code to avoid modifying the original array when changing the copy.

C Sharp (C#)
int[] original = {1, 2, 3};
int[] copy = (int[])original[1];
copy[0] = 10;
Console.WriteLine(original[0]);
Drag options to blanks, or click blank then click option'
AClone()
BCopyTo()
CResize()
DClear()
Attempts:
3 left
💡 Hint
Common Mistakes
Using methods that only copy references or clear the array.
3fill in blank
hard

Fix the error in the code to prevent shared reference issues with objects.

C Sharp (C#)
class Person {
    public string Name;
}

Person p1 = new Person { Name = "Alice" };
Person p2 = p1;
p2.Name = "Bob";
Console.WriteLine([1].Name);
Drag options to blanks, or click blank then click option'
Anull
Bp2
Cnew Person()
Dp1
Attempts:
3 left
💡 Hint
Common Mistakes
Assuming p1 and p2 are independent objects after assignment.
4fill in blank
hard

Fill both blanks to create a deep copy of a list of objects to avoid shared references.

C Sharp (C#)
List<Person> original = new List<Person> { new Person { Name = "Anna" } };
List<Person> copy = original.Select(p => new Person [1]).ToList();
copy[0].Name = [2];
Console.WriteLine(original[0].Name);
Drag options to blanks, or click blank then click option'
A{ Name = p.Name }
B"Elsa"
C"Anna"
D{ Name = "Elsa" }
Attempts:
3 left
💡 Hint
Common Mistakes
Copying the list without copying the objects inside.
5fill in blank
hard

Fill all three blanks to correctly clone a dictionary and modify the copy without affecting the original.

C Sharp (C#)
Dictionary<string, int> original = new Dictionary<string, int> { {"a", 1}, {"b", 2} };
Dictionary<string, int> copy = original.ToDictionary([1], [2]);
copy["a"] = [3];
Console.WriteLine(original["a"]);
Drag options to blanks, or click blank then click option'
Apair => pair.Key
Bpair => pair.Value
C10
D1
Attempts:
3 left
💡 Hint
Common Mistakes
Modifying the original dictionary by mistake due to shared references.