Ekin Karadağ

In this article aimed at those looking to improve their programming skills, as well as students and professionals in the field of software development, you will find details on the differences between Primitive Types and Reference Types in terms of how they are stored in memory, along with some of the problems these differences can create and how to address them.

The main difference between Primitive Data Types and Reference Data Types lies in the way they are stored in memory.

What is the difference between how Primitive and Reference Types are stored in memory?

Primitive types are stored on a stack in memory. They have default values when no value is entered (Integer 0, Double 0.0, etc.).

Reference types, on the other hand, store data in memory at the location pointed to by the address instead of the value. In other words, if an expression contains reference types, the processing of the object is done through the object’s address.

And what does this difference tell us?

In primitive types, equality expressions check the values contained in variables, while in reference types they check whether the addresses of objects are equal.

Now let’s examine this in code.

In C#, when an array is assigned to another array, the memory address of the array is actually passed. This means that array b will point to the same memory region as array a.

Therefore, changes to array b actually affect the same array in memory and these changes are reflected in array a. This implies that arrays a and b share the same memory region.

Meaning, when an assignment operation is performed between two arrays, only the memory address is transferred, and therefore both arrays are linked to process the same data (note that int is a reference type).

If you don’t want this to happen, you can copy the array and operate on it, so that the array will point to a separate address in memory and changes you make will not affect both arrays at the same time.

In the first section, we examined the difference between the ways Primitive Types and Reference Types are stored in memory. In the second section, we will look into why it is necessary to override the Equals and GetHashCode methods.

Stay tuned for the rest of the article