Sobes.tech
Junior — Middle

How is memory managed and structured in the C# environment?

sobes.tech AI

Answer from AI

In C#, memory management is handled automatically by the garbage collector (GC). Memory is divided into two main areas:

  • Stack — stores local variables and method parameters. Memory is allocated and freed very quickly following the LIFO principle.
  • Heap — stores objects and data that live longer than the method execution. Memory on the heap is managed by the garbage collector.

The garbage collector periodically frees memory occupied by objects that are no longer referenced. This relieves developers from manually managing memory and reduces the risk of leaks.

Example of creating an object on the heap:

class Program
{
    static void Main()
    {
        Person p = new Person(); // object is created on the heap
    }
}

class Person
{
    public string Name { get; set; }
}

Here, the Person object is created on the heap, and the variable p is on the stack, referencing this object.