Skip to content
Search lessons, topics, tests…
Esc

    ↑ ↓ moveEnter openEsc close
    Lesson1 / 23

    Module 1 · Values, References and Objects · Lesson 1 of 23

    Value Types vs Reference Types in C#: What a Variable Really Holds

    What this lesson teaches

    Value types vs reference types in C# comes down to what a variable holds. Learn what assignment copies and why some changes affect another variable.

    A value-type variable holds the data itself, as Microsoft's value types documentation explains. A reference-type variable holds a reference to an object, or null. A reference identifies an object, a bit like an address identifies a house.

    This distinction explains more than assignment. It also explains what happens when you pass an argument to a method or return a result.

    By the end, you can predict:

    • Whether two variables contain separate data or refer to one object.
    • What a caller sees when a method changes an object and then replaces its parameter.
    • What happens when a struct contains a list.
    • How strings, records, and nullable value types fit these rules.

    Each program below runs independently on .NET 10. Predict its output before running it. This lesson focuses on copying and sharing, not where data is stored in memory.

    What a variable holds

    For this lesson, think of a variable as a storage location. The important question is what goes into that location.

    With a value type, the location contains the value's data. For a struct, that includes its fields. A field is a variable declared as part of a struct or class.

    With a reference type, the location contains a reference, not the object's data. Copying that reference gives another variable access to the same object. It does not create another object.

    OperationValue-type variableReference-type variable
    Assign it to another variableCopies the valueCopies the reference
    Change a numeric field through the copyOnly the copy changesBoth variables see the change to the same object
    Assign a replacement to one variableReplaces that variable's valueReplaces that variable's reference

    Objects have identity: two separately created objects can remain distinct even when their properties contain identical data. A struct copy gives you a separate value, not a second name for the original variable.

    That last point needs one qualification: separate struct values can still contain references to the same object. We will see that with a list.

    See assignment in four steps

    The program uses a Point struct and a Marker class. An alias here means another variable referring to the same object.

    Watch for two different actions: changing an object and making a variable refer to a different object.

    C#Runs
    var first = new Point { X = 1, Y = 2 };
    var second = first;
    second.X = 9;
    Console.WriteLine($"1. Points: first.X={first.X}; second.X={second.X}");
    
    var marker = new Marker { Label = "start" };
    var alias = marker;
    Console.WriteLine($"2. Shared: marker={marker.Label}; alias={alias.Label}; same={ReferenceEquals(marker, alias)}");
    
    alias = new Marker { Label = "replacement" };
    Console.WriteLine($"3. Rebound: marker={marker.Label}; alias={alias.Label}; same={ReferenceEquals(marker, alias)}");
    
    marker.Label = "changed";
    Console.WriteLine($"4. Changed: marker={marker.Label}; alias={alias.Label}");
    
    public struct Point
    {
        public int X;
        public int Y;
    }
    
    public class Marker
    {
        public string Label { get; set; } = "";
    }
    Output
    1. Points: first.X=1; second.X=9
    2. Shared: marker=start; alias=start; same=True
    3. Rebound: marker=start; alias=replacement; same=False
    4. Changed: marker=changed; alias=replacement

    Step 1: copy the point. Assignment copies both fields, X and Y. Changing second.X then affects only second.

    Step 2: copy the marker reference. There is one marker object. Both variables refer to it. ReferenceEquals checks whether two references identify the same object, so the second output line reports same=True.

    flowchart LR
        M["marker"] -->|"refers to"| O["Marker: start"]
        A["alias"] -->|"refers to"| O

    Step 3: replace one reference. The assignment to alias creates a different marker and stores its reference in alias. It does not modify the original marker. The third line reports same=False.

    flowchart LR
        M["marker"] -->|"refers to"| O["Marker: start"]
        A["alias"] -->|"refers to"| R["Marker: replacement"]

    After step 3, each variable refers to a different marker object.

    Step 4: change the original object. Setting marker.Label changes the original marker to changed. The replacement marker still contains replacement.

    The operation in step 4 is called mutation: changing an existing object's data. It differs from replacing a variable's reference.

    The mistake to avoid. Copying a class variable does not copy the object. Reassigning the copied variable also does not redirect the original variable.

    In an interview, say: “A value-type variable holds its data, and assignment copies that data. A reference-type variable holds a reference or null. Assignment copies the reference, so both variables point to the same object. Changing that object is different from replacing one variable's reference.”

    Parameters and returns copy too

    Ordinary parameters are passed by value: the method receives a copy of what the caller supplies. For a class argument, that copy is a reference.

    An ordinary return also supplies a value to the caller. Returning a class instance supplies a reference; it does not copy the object's properties into a new object.

    Predict the caller's label and the two point coordinates here.

    C#Runs
    var marker = new Marker { Label = "original" };
    ChangeMarker(marker);
    Console.WriteLine($"Caller marker: {marker.Label}");
    var returnedMarker = Echo(marker);
    Console.WriteLine($"Return shares marker: {ReferenceEquals(marker, returnedMarker)}");
    var point = new Point { X = 1 };
    var moved = Move(point);
    Console.WriteLine($"Points: original={point.X}; returned={moved.X}");
    
    static void ChangeMarker(Marker item)
    {
        item.Label = "edited";
        item = new Marker { Label = "replacement" };
    }
    
    static Marker Echo(Marker item)
    {
        return item;
    }
    
    static Point Move(Point item)
    {
        item.X = 20;
        return item;
    }
    
    public class Marker
    {
        public string Label { get; set; } = "";
    }
    
    public struct Point
    {
        public int X;
    }
    Output
    Caller marker: edited
    Return shares marker: True
    Points: original=1; returned=20

    When ChangeMarker starts, item and marker refer to the same object. Setting item.Label changes that shared object.

    The next assignment replaces only the reference in item. The caller still refers to the edited original, so it prints edited, not replacement.

    Echo returns a reference to that same object. The identity check therefore prints True.

    Move receives a separate point value. It changes that copy and returns it. The caller keeps its original point with X=1 and receives another point with X=20.

    Pass by reference means a parameter gives the method access to the caller's variable itself. The ref modifier requests that separate contract and can allow the method to replace the caller's reference. A reference type does not request it automatically.

    See Microsoft's method parameters and modifiers for the full rules.

    The mistake to avoid. “Reference type” does not mean “passed by reference.” A normal class parameter receives a copied reference, not access to replace the caller's variable.

    In an interview, say: “The caller sees the property change, but not the replacement object. The parameter received a copy of the reference. Both references initially reach the same object, but assigning a new object to the parameter changes only the parameter.”

    A struct can contain a shared list

    Copying a struct copies every field. If a field holds a reference, copying that field copies the reference, not the referenced object.

    This is a shallow copy: the copy does not also make independent copies of the objects reached through its fields.

    The same distinction matters for readonly. A readonly field cannot normally be assigned a different value after construction. In the example below, you can assign Members where it is declared or inside ReadingGroup's constructor, but cannot replace it afterward. It does not prevent changes inside an object the field refers to.

    C#Runs
    var first = new ReadingGroup(new List<string> { "Ada" });
    var second = first;
    second.Members.Add("Lin");
    Console.WriteLine($"Counts: first={first.Members.Count}; second={second.Members.Count}");
    Console.WriteLine($"Same list: {ReferenceEquals(first.Members, second.Members)}");
    
    second = new ReadingGroup(new List<string> { "Sam" });
    Console.WriteLine($"After replacement: first={first.Members.Count}; second={second.Members.Count}");
    
    public readonly struct ReadingGroup
    {
        public readonly List<string> Members;
    
        public ReadingGroup(List<string> members)
        {
            Members = members;
        }
    }
    Output
    Counts: first=2; second=2
    Same list: True
    After replacement: first=2; second=1

    The copied ReadingGroup contains a copy of the Members reference. Both groups therefore reach one list.

    Calling Add through second.Members changes that list. Both counts become 2, and the identity check prints True.

    A readonly struct requires its instance fields to be readonly. An instance field belongs to each value; a static field belongs to the type. That protects the fields from reassignment after construction, but the list remains changeable. Calling Add does not assign a new reference to Members.

    Finally, replacing second gives that variable a different group containing a different list. The first group still reaches the two-member list.

    The mistake to avoid. Neither copying a struct nor marking it readonly makes every object it refers to independent or unchangeable.

    In an interview, say: “Copying a struct containing a List copies the list reference. Both struct values share the same list, so adding through either copy affects that list. Readonly is shallow too: it prevents replacing the field, not changing the list.”

    Which types are value types and reference types?

    You can usually tell from the keyword: struct and enum declare value types. class, delegate, and record without struct declare reference types. Tuples, records, and strings look special, but follow the same copy rules.

    A value tuple groups values using syntax such as (int X, int Y) and is a value type. A delegate is an object representing a callable method, possibly together with the object that method uses.

    A record is a class or struct declaration that supplies features for working with data, including generated comparisons. Value equality means comparing the data chosen by the type's equality rules rather than requiring the same object identity.

    Value typesReference types
    Structs and enumsClasses
    Numeric types, bool, and charstring and object
    Value tuplesArrays, including arrays of structs
    record structDelegates and record class

    record without struct declares a record class. It is a reference type even though its generated equality compares data.

    C#Runs
    var firstValue = new PositionValue(1);
    var secondValue = firstValue;
    secondValue.X = 8;
    Console.WriteLine($"Record structs: first={firstValue.X}; second={secondValue.X}");
    
    var firstObject = new PositionObject { X = 1 };
    var secondObject = firstObject;
    secondObject.X = 8;
    Console.WriteLine($"Record classes: first={firstObject.X}; second={secondObject.X}");
    
    public record struct PositionValue(int X);
    
    public record class PositionObject
    {
        public int X { get; set; }
    }
    Output
    Record structs: first=1; second=8
    Record classes: first=8; second=8

    The record struct assignment copies its data; the record class assignment copies its reference, so both variables see X=8.

    The generated comparison behavior does not change either assignment rule. For comparisons themselves, continue with Equals vs == vs ReferenceEquals in C#.

    The mistake to avoid. “Record” does not identify one type category. Check whether the declaration is a record class or a record struct.

    In an interview, say: “A record class is a reference type with generated value equality. A record struct is a value type. Their equality features do not change what assignment copies: a reference for the class, and the data for the struct.”

    Why string can look like a value type

    string is a reference type. Its behavior can be misleading because strings are immutable: an existing string object's text cannot be changed after creation. Microsoft's Strings programming guide explains this rule.

    Assigning different text to a string variable changes which string it refers to. It does not edit the original string object.

    C#Runs
    string first = "red";
    string second = first;
    second = second.ToUpperInvariant();
    Console.WriteLine($"Strings: first={first}; second={second}");
    
    string sameText = new string(new[] { 'r', 'e', 'd' });
    Console.WriteLine($"Same contents: {first == sameText}");
    Output
    Strings: first=red; second=RED
    Same contents: True

    Initially, first and second refer to the same string. ToUpperInvariant supplies uppercase text, and the assignment makes second refer to the result. first still refers to red.

    The final line prints True because string == compares text contents. That comparison does not make strings value types. Microsoft's string documentation explains these special behaviors.

    The mistake to avoid. Independent-looking string assignments and content comparisons do not prove that string is a value type. Immutability prevents the shared-object changes seen with Marker.

    In an interview, say: “No, string is a reference type. It is immutable, so changing a string variable replaces its reference rather than editing the existing string. String == compares contents, which is separate from how assignment works.”

    Defaults and nullable value types

    A default value is the value C# supplies when you use default for a type. For a struct, each field receives its own default: numeric fields become zero, bool fields become false, and reference fields become null.

    The default for a reference type is null, not a newly created object. C# does not automatically give local variables a default value. You must give a local variable a value before reading it. See Microsoft's default values documentation.

    An ordinary value type such as int cannot hold null. A nullable value type, written T? or Nullable<T>, adds the ability to represent no value. For example, int? contains a HasValue flag (true or false) and, when that flag is true, an ordinary int value.

    C#Runs
    Point point = default;
    Console.WriteLine($"Default point: X={point.X}; Y={point.Y}");
    Console.WriteLine($"Default Marker is null: {default(Marker) is null}");
    
    int? missing = null;
    int? present = 7;
    Console.WriteLine($"Missing has value: {missing.HasValue}");
    Console.WriteLine($"Present has value: {present.HasValue}");
    if (present.HasValue)
    {
        Console.WriteLine($"Present value: {present.Value}");
    }
    
    public struct Point
    {
        public int X;
        public int Y;
    }
    
    public class Marker
    {
    }
    Output
    Default point: X=0; Y=0
    Default Marker is null: True
    Missing has value: False
    Present has value: True
    Present value: 7

    Reading Value when HasValue is false throws an exception.

    Despite its ability to represent null, int? remains a value type. See nullable value types for more examples.

    The mistake to avoid. A default struct is not a null reference. You can write int? or Point?, but Nullable<T> requires a value type that is not already nullable. It does not work with classes, whose variables can already hold null. On a class, Marker? is a nullable reference type annotation: a compile-time warning hint, not a Nullable<T> wrapper.

    In an interview, say: “A struct's default has default-valued fields, while a reference type's default is null. A non-nullable value type cannot hold null. For example, int? uses HasValue to say whether an int value is present.”

    Check yourself

    A normal method parameter receives a Marker object. The method changes its Label, then assigns a new Marker to the parameter. What does the caller see?

    A The original Marker with its changed Label
    B The replacement Marker
    C The original Marker with its unchanged Label
    D null
    Show answer

    Correct answer: A

    The parameter receives a copy of the reference. The property change affects the shared object, but reassigning the parameter does not replace the caller's reference.

    A readonly struct contains a readonly List<int> field. After copying the struct, you call Add through the copied field. What happens?

    A It does not compile: readonly forbids calling Add
    B Both structs share one list, now holding the item
    C Only the copied struct's list gets the new item
    D The copy made its own list, so only that list grows
    Show answer

    Correct answer: B

    The field's reference is copied. Readonly prevents replacing that field after construction, but it does not prevent changing the list it refers to.

    Going deeper

    Every struct and enum derives, directly or indirectly, from System.ValueType. Every class other than object derives, directly or indirectly, from object. Microsoft's value types documentation explains this relationship.

    Struct or Class in C# shows how to choose between a struct and a class.

    Immutable structs are often easier to use because an unnoticed copy cannot later diverge through field changes. That is a design recommendation, not a requirement: the mutable points in this lesson deliberately make copying visible.

    Microsoft's Choosing Between Class and Struct recommends small, immutable structs representing a single value. It is older guidance, and its size thresholds are design advice rather than C# limits. That page also says “reference types are passed by reference”; read it as “the reference is copied”. Ordinary class arguments are passed by value too, as the method-parameter documentation linked earlier explains.

    Measured on .NET 10.0.12 x64, an int? and a reference each take 8 bytes. Sizes like these are details of CoreCLR, the engine that runs .NET code, on x64 processors—not C# rules.

    Sources

    Practice

    Practice test: Practice: Value Types vs Reference Types in C#: What a Variable Really Holds10 questions · 1 mark each, no negative markingFull Access
    Take the test
    Sign in to mark lessons done and keep your place in the course.Sign in

    Checked before publishing: C# examples run on .NET 10, links opened, reviewed while it was written and read in full. How lessons are checked

    Updated 1 Dec 2026 ·