This week, I was focused on improving my knowledge of C# based on the mock interview of the last week with the topics that my interviewer recommended to me, mainly how the stack and heap memory work in this programming language.
Stack and Heap memory
This is a very important topic to know how those two memories work in your programming language because some “interesting things” can happen to you by surprise if you’re not familiarized with how the variables and objects are stored inside the memory.
For start, the stack memory is a LIFO system, agile and organized, here are stored all the primitive type variables, for example, ints, floats, doubles, strings, etc.
On the other hand, is heap memory, which is used to store the values of the objects, but to keep track of where is this written, the address (or pointer) of the information is written in the stack memory.
This makes a set of interesting scenarios playing with the memory and how it is handled.
To start, this makes diversification of how the variables are passed throw the functions.
When you pass a variable, you’re passing the value of the stack memory, this means that if you pass an int after the function the value stays the same.
This is known as passing a variable by value.
But, if you pass an object to a function, you have to be careful, because as we said before, you’re only passing the stack value, which means, the memory address of the heap memory.
In other words, you are editing the object inside the function, and the properties will be overwritten.
Difference of class and struct
Related to this topic is one of the prior differences between a class and a struct.
This is where the variables are located in the memory, as we said before, the objects are stored in the heap memory, but the structs are stored at the stack memory, as a primitive variable.
So, you can play with this for your advantage at the hour of programming.
In order to understand better how the stack and heap memory works I realized a little code playing with the features described before: