Understanding the stack and heap in C#

Click for: original source

Based on my reading, “the stack” and “the heap” are clearly important concepts for understanding how memory is managed in C# programs, however until recently I had only a superficial understanding of them and their role. By Liam Mooney.

This is a basic class with two fields that are being initialised by a constructor

Source: https://endjin.com/blog/2022/07/understanding-the-stack-and-heap-in-csharp-dotnet.html

The article makes a good job explaining:

  • What is “the stack”?
  • What is “the heap”?
  • Thinking about variables and program memory
  • Value types vs reference types
  • So where do C# variables get stored?
  • There are exceptions

The defining property of stacks is that they’re last-in, first-out, meaning the last item added to the stack is the first item to be removed. In other words, to place a new item onto a stack it has to go on the top, and only the item currently at the top can be removed, therefore if you wanted to remove an item from the middle of a stack, say, the third item down from the top, you would first have to remove the top two items.

Excellent read with plenty of code examples and charts helping you to understand the concepts better!

[Read More]

Tags programming performance app-development code-refactoring