Garbage collection in C# with example

Garbage collection in C# is the automatic process of managing memory by identifying and reclaiming objects that are no longer needed, freeing up memory for reuse. It helps prevent memory leaks and makes memory management more efficient. Here's a simple example:

```csharp
class MyClass
{
    public int Data;
    
    public MyClass(int value)
    {
        Data = value;
    }
}

class Program
{
    static void Main()
    {
        MyClass obj1 = new MyClass(42); // Create an object
        MyClass obj2 = new MyClass(84); // Create another object

        // Now, let's assume we no longer need obj1
        obj1 = null; // Set obj1 to null to indicate it's no longer referenced

        // At this point, the garbage collector may identify obj1 as unreachable
        // and free the memory associated with it, since it's not used anymore.

        // The memory for obj2 is still in use because it's referenced by obj2.
        
        // You don't have to explicitly free memory; C#'s garbage collector handles it.
    }
}
```

In this example, `obj1` is set to `null`, which means it's no longer accessible. The garbage collector will eventually identify that it's unreachable and reclaim the memory. This process of reclaiming memory is automated and transparent to the programmer.

Comments

Popular posts from this blog

How to maintain state in asp.net core

What is react and vite

How to find 2nd highest salary simple way in sql server