Goal
Show the difference between:
-
Structs (value types): copies need to be written back
-
Classes (reference types): mutations via any reference affect the same object
Tasks
-
Create
PointSas a struct andPointCas a class, each withint X, Y. -
Write three methods:
-
MoveFirstWrong(PointS[] arr): read the first element into a local, add10toX/Y, don’t write it back (bug). -
MoveFirstRight(PointS[] arr): same as above, but assign back toarr[0](fix). -
MoveFirstRef(PointC[] arr): mutatearr[0].X/.Ydirectly (works because it’s a reference type).
-
-
Demonstrate the difference with
Console.WriteLinebefore/after each call. -
(Optional mini-task) Show the same bug pattern with a
List<PointS>in aforeach: copy to a temp, modify, and forget to assign back.
Checkpoint
Your output must show the struct refusing to change and the class changing:
-
MoveFirstWrongleaves the array element at(1,1). Nothing throws, nothing warns, and that silence is the entire bug. -
MoveFirstRightleaves it at(11,11). -
MoveFirstRefon the class array reaches(11,11)without any write-back, becausearr[0]hands you the object rather than a copy of it. -
The optional
List<PointS>pair goes(5,5)then still(5,5)then(6,6).
If the Wrong methods produce the same result as the Right ones, you declared PointS as a class by accident.