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

Reference assignment and shared state in C Sharp (C#) - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What happens when you assign one reference type variable to another in C#?
Both variables point to the same object in memory, so changes through one variable affect the other.
Click to reveal answer
beginner
Explain shared state in the context of reference assignment.
Shared state means multiple variables refer to the same object, so modifying the object via any variable changes the state seen by all.
Click to reveal answer
beginner
Consider this code:<br><pre>class Box { public int Value; }<br>Box a = new Box();<br>a.Value = 5;<br>Box b = a;<br>b.Value = 10;</pre><br>What is the value of <code>a.Value</code> after this code runs?
The value of a.Value is 10 because a and b reference the same object.
Click to reveal answer
intermediate
How can you avoid shared state when working with reference types?
Create a new object (a copy) instead of assigning the reference, so each variable points to a separate object.
Click to reveal answer
beginner
Why is understanding reference assignment important in programming?
Because it helps prevent bugs caused by unexpected changes to shared objects and helps manage how data is shared or isolated.
Click to reveal answer
What does assigning one reference variable to another do in C#?
ABoth variables point to the same object.
BCreates a new copy of the object.
CDeletes the original object.
DCopies only the values, not the reference.
If you change a property of an object through one reference, what happens to other references to the same object?
AThey point to a new object.
BThey see the updated property value.
CThey become null.
DThey keep the old property value.
How can you create a separate object to avoid shared state?
ADeclare the variable as static.
BAssign one reference to another.
CUse the 'ref' keyword.
DUse the 'new' keyword to create a new instance.
Which of these is a value type in C# that does NOT share state on assignment?
Aclass
Bstring
Cint
Darray
What is a common problem caused by shared state?
AUnexpected changes to data.
BCompilation errors.
CSlower program startup.
DSyntax errors.
Describe what happens when you assign one reference type variable to another in C# and how it relates to shared state.
Think about how variables point to objects in memory.
You got /4 concepts.
    Explain how you can avoid shared state when working with objects in C#.
    Consider how to make variables point to different objects.
    You got /4 concepts.