Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 1

C# Value vs. Reference Types

Recommended resources

Hello! Welcome to the start of our crash course to prepare you for your upcoming technical interview. We'll be moving quickly, focusing on the C# and OOP concepts that are critical for the junior full-stack role you're targeting.

Our first lesson tackles a fundamental concept in C# that is a very common interview question: the distinction between value types and reference types. By the end of this session, you will be able to distinguish between them, explain how they are managed in memory, and describe how their differences in behavior affect your code. Given your background in computer science, the underlying memory concepts of the stack and heap should be familiar, which will allow us to focus specifically on how the C# type system utilizes them.

1. The Two Categories of Types in C#

In C#, every data type is either a value type or a reference type. This classification dictates where a variable's data is stored in memory and how it behaves when you assign it or pass it to a method.

  • Value Types: These types directly contain their data. Think of them as a box holding a value. Examples include primitive types like int, double, bool, and custom types you define with the struct keyword.
  • Reference Types: These types do not store their data directly. Instead, they store a reference (essentially a memory address) to where the data is located. The data itself resides elsewhere. Examples include string, object, arrays, and any custom type you define with the class keyword.

This diagram illustrates the C# type hierarchy. Notice that both ValueType and other reference types like class ultimately derive from System.Object, but they are handled very differently by the runtime.

This diagram shows that all types in C# inherit from `System.Object`. Value types, like `int` and user-defined `struct`s, form one branch, while reference types, like `string`, `array`, and user-defined `class`es, form another.

2. Memory Allocation: The Stack vs. The Heap

The key to understanding the difference between value and reference types lies in where they live in memory: the stack and the heap.

  • The Stack: A highly efficient, LIFO (Last-In, First-Out) region of memory. It's used for static memory allocation—meaning the size of what's stored must be known at compile time. Variables on the stack are short-lived; they exist only for the duration of the method call in which they are declared. Management is simple: the stack pointer is just moved up or down.
  • The Heap: A large region of memory used for dynamic allocation, where data can be created and destroyed in any order. Its lifetime is not tied to a specific method call. Memory on the heap must be managed, and in C#, this is handled automatically by the Garbage Collector (GC).

The general rule of thumb is that value types are allocated on the stack, while the data for reference types is allocated on the heap. However, the full story is more nuanced and is a great point to clarify in an interview.

This image illustrates how local variables for a method call are placed on the stack. For value types (`c1`, `c2`, `c3`), their actual values are on the stack. For the reference type `c4`, a *reference* is stored on the stack, which points to the actual `ClassX` object located on the heap.

Let's dive into a more detailed video explanation of this memory model. The following segment visually demonstrates how the stack pointer works and how objects on the heap are managed by the garbage collector.

C# Value Types and Reference Types

Watch this segment from the "C# Value Types and Reference Types" video by Coding Tutorials. It provides an excellent visual walkthrough of how the stack and heap are used for structs (value types) and classes (reference types).

Please watch from this section. Pay close attention to the animation of the stack pointer and the explanation of what happens to heap objects when they are no longer referenced.

Now, let's solidify this with a short reading that directly addresses a common interview misconception.

Interview question: heap vs stack (C#)

This article from DEV Community corrects a common oversimplification you might hear about value and reference types. Understanding this nuance will help you provide a more precise answer in your interview.

Focus on the first part of the article, from the beginning down to the end of the initial explanation of value types. Specifically, read the answer to the question "Which objects are allocated...". Note the crucial point: reference types are always on the heap, but value types can be on either the stack or the heap (e.g., if a value type is a field within a class, it lives on the heap as part of that class object).


3. How This Affects Behavior

The difference in memory allocation leads to profound differences in how these types behave, especially concerning assignment and parameter passing.

Assignment Behavior

  • When you assign a value type variable to another, the value is copied. You end up with two independent variables, each with its own copy of the data.
  • When you assign a reference type variable to another, the reference is copied, not the object itself. You end up with two variables pointing to the same object on the heap.

This is best understood with a code example.

// Value Type Example (structs or primitives like int)
int a = 50;
int b = a; // The value 50 is copied into b.

b = 100; // This changes b only.
// At this point, a is still 50, and b is 100. They are independent.

// ---

// Reference Type Example (classes)
public class Wallet { public int Money { get; set; } }

Wallet wallet1 = new Wallet { Money = 50 };
Wallet wallet2 = wallet1; // The reference (address) is copied. Both variables point to the same Wallet object.

wallet2.Money = 100; // This changes the Money property of the single object on the heap.
// At this point, wallet1.Money is also 100, because wallet1 and wallet2 refer to the same object.

Parameter Passing

This same logic applies when you pass variables to methods.

  • Passing a value type to a method creates a copy of it for the method to use. Changes inside the method do not affect the original variable.
  • Passing a reference type to a method copies the reference. The method can use this reference to modify the original object.

The following video segment demonstrates this concept clearly with ProcessPoint (value type) and ProcessPerson (reference type) methods.

C# Value Types and Reference Types

Let's return to the "C# Value Types and Reference Types" video to see a practical demonstration of these behavioral differences.

Watch the segments on parameter passing and on variable assignment. Observe how modifying the variable inside the ProcessPoint method doesn't affect the original, while modifying the Person object affects all references to it.


4. Important Interview Nuances

To really stand out, you should be aware of a few more advanced topics related to this concept.

1. Equality Comparison (== vs. .Equals()):

  • For reference types, the == operator, by default, checks for reference equality (do two variables point to the same object?). To check for value equality (do two different objects have the same property values?), you typically override the .Equals() method.
  • For value types, == performs value equality, but you often have to provide the implementation by overloading the operator.

2. The Special Case of string:
The string type is a classic interview question. It's a reference type, but it is immutable (its value cannot be changed after it is created). Operations that appear to modify a string, like s.ToUpper(), actually create a new string object. Furthermore, its == operator is overloaded to perform value comparison. This combination makes it behave very much like a value type, which is intuitive for developers but is a key detail about its implementation.

3. When to Choose struct vs. class:
You use a class by default. You should only consider using a struct if the type:

  • Logically represents a single value (e.g., a point, a color).
  • Is small (generally 16 bytes or less).
  • Is immutable (its values won't change after creation).
  • Will not need to be "boxed" frequently (boxing is the process of converting a value type to a reference type, which has a performance cost).

The following video section provides an excellent discussion on these nuances.

C# Value Types and Reference Types

This final segment covers these crucial interview topics: equality, the design choice between struct and class, and the special case of string.

Watch from equality and design choice, and then the section on the string anomaly. Understanding these will prepare you for follow-up questions.


Conclusion

You've just covered a foundational topic of C# and .NET development. A strong grasp of this material is essential for writing correct and efficient code, and for demonstrating your technical depth in an interview.

Here are the key takeaways:

  • Value Types (struct, primitives): Store data directly, are typically allocated on the stack, and are copied by value on assignment.
  • Reference Types (class, array, string): Store a reference to data that lives on the heap. They are copied by reference on assignment, meaning multiple variables can point to the same object.
  • Memory Model: The stack is for fast, short-lived, compile-time-sized data. The heap is for dynamic, longer-lived data managed by the Garbage Collector.
  • Behavioral Impact: The core distinction affects variable assignment, parameter passing, and how equality is checked.
  • The string Exception: Remember that string is an immutable reference type that often behaves like a value type, which is a common point of discussion.

In our next lesson, we will begin to look inside these classes and structs. We'll explore how to define their members (fields and methods) and control their visibility using access modifiers, which is the next logical step in understanding object-oriented programming in C#.