Junior — Middle
Kuidas hallatakse ja struktureeritakse mälu C# keskkonnas?
sobes.tech AI
Vastus AI-lt
In C#, memory management is performed automatically using 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 time. Heap memory is managed by the garbage collector.
The garbage collector periodically frees memory occupied by objects that no longer have references. This relieves the developer from manual memory management 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, while the variable p is on the stack, referencing this object.