↓ Ir para o conteúdo principal

← todas as notas

📎 Webclip

How C# Manages Memory Automatically

C# handles memory through garbage collection, so objects do not need manual allocation and deallocation. The text says the collector allocates objects on the heap, checks how many references point to them, and reclaims memory when objects are no longer reachable.

It also explains that collection is generation-based, with younger objects collected more often than older ones. For disposable resources, a using statement ensures Dispose is called, as shown with FileStream.

Reading notes
#

  • Memory management in C# is handled automatically by garbage collection.
  • Objects are allocated on the heap when they are created.
  • The collector tracks references to objects and makes an object eligible for collection when it has no references.
  • C# uses a generation-based approach, with younger objects collected more frequently.
  • When memory is low, the collector scans the heap and reclaims unreachable objects.
  • In the example, when the reference to person1 is lost, the object becomes eligible for collection.
  • The using statement is used to dispose of a FileStream properly, even if an exception occurs.
  • When the using block exits, Dispose is called automatically and file resources are released.
  • The text notes that setting a reference to null can help make an object eligible for garbage collection.
  • Excessive object creation and retention can lead to unnecessary garbage collection cycles and performance issues.