Skip to content
Search lessons, topics, tests…
Esc

    ↑ ↓ moveEnter openEsc close
    Lesson3 / 41

    Value vs reference semantics, and method call stack frames

    Review task

    Trace the rename through caller, parameter and result references. Show the object count before and after an explicit copy, and identify which destination is assigned only on return. Your review should explain the shared object without relying on a physical stack-layout claim.

    Attempt before checking the reference

    Case 1: Value semantics and reference semantics are assignment rules

    Predict

    What exactly does TaskCard second = first copy, and how many TaskCard objects exist afterward?

    Change

    Add a Copy method or copy constructor to TaskCard. Demonstrate that changing the copy does not alter the original.

    Constraint

    Copy only the state currently present. Do not introduce records yet; make object creation explicit.

    Case 2: A method call creates a new stack frame story

    Predict

    When NormalizeTitle starts, which frame owns rawTitle, which frame owns title, and what happens when the method returns?

    Change

    Draw the frames for Main -> CreateTask -> NormalizeTitle. Put each parameter and local in the correct frame, then mark the return path.

    Constraint

    Use the shown method signatures and bodies; do not invent global fields. For the illustrative Main -> CreateTask -> NormalizeTitle chain, distinguish supplied values from assumptions rather than inventing unseen locals.

    Check the decision

    TaskCard second = first is followed by second.Title = "Write tests". What was copied by the assignment?

    A A reference to the same TaskCard object.
    B The entire object graph.
    C A second independent Title property slot in a new object.
    D A permanent alias between the two variable storage locations.
    Show answer

    Correct answer: A

    Ordinary reference assignment copies a reference value. Both variables identify one object, while each variable can later be reassigned independently.

    Hint: Draw variables and objects as different things.

    Trace the contract

    OperationTaskCard objectsObservable title
    second = firstOneBoth references observe the same mutable card
    new TaskCard(first.Title)TwoEach card can replace its own title reference
    A method returns a referenceNo automatic object cloneThe caller receives a copied reference value
    A nested mutable member is added laterCopy policy needs another decisionA shallow object copy may still share that member

    Reference cases

    Value semantics and reference semantics are assignment rules

    One concept

    Value-type assignment copies data; reference-type assignment copies a reference to the same object.

    Mental model

    Do not equate value type with stack or reference type with heap. The useful question is: what does assignment copy?

    For ordinary assignment, a value-type variable stores the value, while a reference-type variable stores a reference. Copying that reference makes both variables refer to the same object; it does not make the variables themselves aliases. A struct copy is also shallow: reference-valued fields still refer to the same nested objects.

    MENTAL MODEL DIAGRAM

    Text
    value assignment          reference assignment
    
    priorityA [ 2 ]           first  [ ref 0xA ] --+
                                                   +--> TaskCard
    priorityB [ 2 ]           second [ ref 0xA ] --+
    
    change B -> A unchanged   mutate through second -> first observes it

    TaskFlow: bad vs good

    BAD - a copied reference is mistaken for a copied object

    Use the TaskCard class declared in the good example for either snippet; run the alternatives separately.

    C#
    TaskCard first = new("Fix export");
    TaskCard second = first;
    second.Title = "Delete production";
    Console.WriteLine(first.Title);

    GOOD - copy intent is explicit

    C#
    TaskCard first = new("Fix export");
    TaskCard second = new(first.Title);
    second.Title = "Write regression test";
    Console.WriteLine(first.Title); // Fix export
    
    public sealed class TaskCard(string title)
    {
        public string Title { get; set; } = title;
    }

    The bad example has one TaskCard and prints Delete production. The good example has two cards and prints Fix export. Both initially refer to the same immutable title string, which is safe here: assigning second.Title replaces only that property’s reference. This is not a general deep-copy implementation for future mutable child objects.

    What beginners get wrong

    They say 'classes live on the heap' and stop thinking. That does not explain aliasing, boxing, fields inside objects, or compiler optimizations.

    What breaks in production

    One request mutates an object cached or shared by another request, producing race conditions, stale views, and audit records that no longer match the original command.

    A method call creates a new stack frame story

    One concept

    A normal synchronous invocation can be modeled as a logical frame containing parameters, locals, and a return point.

    Mental model

    Picture a stack of active synchronous conversations. The caller waits for the callee to return or throw. Ordinary value parameters receive copies of argument values (including copied references); ref, out, and in parameters use by-reference semantics instead. The JIT may inline or optimize frames, so this is not an exact physical-layout or stack-trace guarantee. Captured locals can outlive a call, and async/iterator methods introduce state-machine lifetimes beyond this simple synchronous model.

    MENTAL MODEL DIAGRAM

    Text
    top - currently running
    +----------------------------+
    | NormalizeTitle(title slot) |
    | local: trimmed             |
    +----------------------------+
    | CreateTask(rawTitle slot)  |
    | return point: line 12      |
    +----------------------------+
    | Main(args slot)            |
    +----------------------------+
    bottom - oldest active call

    TaskFlow: bad vs good

    BAD - hidden global state makes call behavior unclear

    These are members inside a class, not top-level local declarations.

    C#
    static string _currentTitle = "";
    static void NormalizeTitle()
    {
        _currentTitle = _currentTitle.Trim();
    }

    GOOD - inputs and outputs tell the frame story

    C#
    static string NormalizeTitle(string rawTitle)
    {
        string trimmed = rawTitle.Trim();
        return trimmed;
    }
    string title = NormalizeTitle(" Fix export ");

    In the good snippet, the callee has its rawTitle parameter and trimmed local. The caller’s title is assigned only when the call returns successfully, yielding Fix export; if the call throws, that assignment does not happen. These examples assume non-null input.

    What beginners get wrong

    They think a method 'jumps away' without tracking argument copies, locals, return values, or which frame an exception is leaving.

    What breaks in production

    Hidden shared state makes methods order-dependent, tests flaky, and concurrent calls overwrite each other's data.

    Sign in to mark lessons done and keep your place in the course.Sign in

    TechInterviewNotes Editorial Team · Updated 28 Oct 2026 ·