Skip to content

Value vs Reference Types

Lost in coding? Discover our Learning Paths!
Lost in coding? Discover our Learning Paths!

Intro

This article extends a lesson from our C# Masterclass about the difference between value and reference types.

 

The difference between value and reference types

In C#, there are two main categories of data types: value types and reference types. The main difference between these two categories is the way that they are stored in memory and how they are accessed in the code.

Value Types: Value types directly contain their data, and when you assign a value type variable to another variable, a new copy of the value is created in memory. Value types are stored on the stack, which is a section of memory that stores short-lived data. Examples of value types include int, bool, float, struct, and enum.

int a = 5;
int b = a;
b = 10;

In this example, the a variable is assigned the value of 5. When b is assigned the value of a, a new copy of the value 5 is created and stored in memory. If we then change the value of b to 10, it does not affect the value of a.

Reference Types: Reference types store a reference to the memory location where the data is stored rather than the data itself. When you assign a reference type variable to another variable, both variables point to the same memory location, and any changes made to the data through one variable will be reflected in the other. Reference types are stored on the heap, which is a section of memory that stores long-lived data. Examples of reference types include string, object, class, and interface.

string a = "Hello";
string b = a;
b = "World"; /// here 'a' reasigned to "World"

In this example, the a variable is assigned the value of "Hello". When b is assigned the value of a, both variables point to the same memory location. If we then change the value of b to "World", the value of a will also be changed to "World".

It’s important to understand the difference between value and reference types in C#, as it affects how the data is stored in memory and how it is accessed and manipulated in your code.

 

 

If you want to skyrocket your C# career, check out our powerful ASP.NET FULL-STACK WEB DEVELOPMENT COURSE, which also covers test-driven development and C# software architecture.

Lost in coding? Discover our Learning Paths!
Lost in coding? Discover our Learning Paths!
Tired of being just an average developer?
Stop wasting your time and learn coding the right (and easy) way!
Tired of being just an average developer?
Stop wasting your time and learn coding the right (and easy) way!
Enter your email and we will send you the PDF guide:
Enter your email and we will send you the PDF guide